private void button1_Click(object sender, EventArgs e)
{
// 上移
if (this.listBox1.SelectedIndices.Count > 0 &&
this.listBox1.SelectedIndices[0] > 0)
{
int[] newIndices =
this.listBox1.SelectedIndices.Cast<int>()
.Select(index => index - 1).ToArray();
this.listBox1.SelectedItems.Clear();
for (int i = 0; i < newIndices.Length; i++)
{
object obj = this.listBox1.Items[newIndices[i]];
this.listBox1.Items[newIndices[i]] = this.listBox1.Items[newIndices[i] + 1];
this.listBox1.Items[newIndices[i] + 1] = obj;
this.listBox1.SelectedItems.Add(this.listBox1.Items[newIndices[i]]);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
// 下移
if (this.listBox1.SelectedIndices.Count > 0 &&
this.listBox1.SelectedIndices[this.listBox1.SelectedIndices.Count - 1] <
this.listBox1.Items.Count - 1)
{
int[] newIndices =
this.listBox1.SelectedIndices.Cast<int>()
.Select(index => index + 1).ToArray();
this.listBox1.SelectedItems.Clear();
for (int i = newIndices.Length; i > 0; i--)
{
object obj = this.listBox1.Items[newIndices[i - 1]];
this.listBox1.Items[newIndices[i - 1]] = this.listBox1.Items[newIndices[i - 1] - 1];
this.listBox1.Items[newIndices[i - 1] - 1] = obj;
this.listBox1.SelectedItems.Add(this.listBox1.Items[newIndices[i - 1]]);
}
}
}
private void button3_Click(object sender, EventArgs e)
{
// 置顶
if (this.listBox1.SelectedIndices.Count > 0 &&
this.listBox1.SelectedIndices[0] > 0)
{
int[] oldIndices =
this.listBox1.SelectedIndices.Cast<int>().ToArray();
int[] newIndices =
this.listBox1.SelectedIndices.Cast<int>()
.Select(index => index - 1).ToArray();
int offest = oldIndices[0];
while (offest-- > 0)
{
this.listBox1.SelectedItems.Clear();
for (int i = 0; i < newIndices.Length; i++)
{
object obj = this.listBox1.Items[newIndices[i]];
this.listBox1.Items[newIndices[i]] = this.listBox1.Items[newIndices[i] + 1];
this.listBox1.Items[newIndices[i] + 1] = obj;
this.listBox1.SelectedItems.Add(this.listBox1.Items[newIndices[i]]);
}
newIndices = newIndices.Select(index => index - 1).ToArray();
}
}
}
private void button4_Click(object sender, EventArgs e)
{
// 置末
if (this.listBox1.SelectedIndices.Count > 0 &&
this.listBox1.SelectedIndices[this.listBox1.SelectedIndices.Count - 1] <
this.listBox1.Items.Count - 1)
{
int[] oldIndices =
this.listBox1.SelectedIndices.Cast<int>().ToArray();
int[] newIndices =
this.listBox1.SelectedIndices.Cast<int>()
.Select(index => index + 1).ToArray();
int offest = oldIndices[oldIndices.Length - 1];
while (offest++ < this.listBox1.Items.Count - 1)
{
this.listBox1.SelectedItems.Clear();
for (int i = newIndices.Length; i > 0; i--)
{
object obj = this.listBox1.Items[newIndices[i - 1]];
this.listBox1.Items[newIndices[i - 1]] = this.listBox1.Items[newIndices[i - 1] - 1];
this.listBox1.Items[newIndices[i - 1] - 1] = obj;
this.listBox1.SelectedItems.Add(this.listBox1.Items[newIndices[i - 1]]);
}
newIndices = newIndices.Select(index => index + 1).ToArray();
}
}
}
Winfrom 中 ListBox如何实现上移下移,置顶 置底的功能
最新推荐文章于 2024-04-12 10:28:23 发布