[C#]Listbox的上移、下移、左移、右移
話說,Vb.Net轉C#真的不是加個大誇號和分號就搞定,有些物件的屬性還不盡相同。趁有時間練習一下C#的一些物件使用,並在此做一下紀錄。
由於感冒藥吃下去快陣亡,所以就廢話不多說,首先是介面的示意畫面,下方是程式碼。
程式碼內都有註解~有需要的朋友可以參考,這個包含了多筆選擇的操控。
///
/// 表單開啟
///
private void Select_Item_Load(object sender, EventArgs e)
{
//給ListBox值
for (int i = 0; i < 10; i++)
{
this.listBox1.Items.Add("★" + i);
}
//調整listbox為可多選
listBox1.SelectionMode = SelectionMode.MultiExtended;
listBox2.SelectionMode = SelectionMode.MultiExtended;
}
///
/// listbox所選項目向右移
///
private void button_right_Click(object sender, EventArgs e)
{
// '檢查有沒有選取項目
if (listBox1.SelectedIndices.Count > 0)
{
//由於被移動後所選取的數量會改變,所以要先放在暫存器內
int selectedCount = listBox1.SelectedIndices.Count;
//用for迴圈由小到大去巡覽
for (int i = 0; i <= selectedCount - 1; i++)
{
//移動後,下一個選取的會變成第一個,所以永遠用index0
int index = listBox1.SelectedIndices[0];
//進行換位置的動作
object tmp = listBox1.Items[index];
listBox1.Items.Remove(tmp);
listBox2.Items.Add(tmp);
}
}
}
///
/// listbox所選項目向左移
///
private void button_left_Click(object sender, EventArgs e)
{
// '檢查有沒有選取項目
if (listBox2.SelectedIndices.Count > 0)
{
//由於被移動後所選取的數量會改變,所以要先放在暫存器內
int selectedCount = listBox2.SelectedIndices.Count;
//用for迴圈由小到大去巡覽
for (int i = 0; i <= selectedCount - 1; i++)
{
//移動後,下一個選取的會變成第一個,所以永遠用index0
int index = listBox2.SelectedIndices[0];
//進行換位置的動作
object tmp = listBox2.Items[index];
listBox2.Items.Remove(tmp);
listBox1.Items.Add(tmp);
listBox1.Sorted = true;
}
}
}
///
/// listbox所選項目向下移
///
private void button_down_Click(object sender, EventArgs e)
{
if (listBox2.SelectedIndices.Count > 0)
{
//用for迴圈由大到小去巡覽
for (int i = listBox2.SelectedIndices.Count - 1; i >= 0; i--)
{
int index = listBox2.SelectedIndices[i];
//如果index為第最後項就不需要下移
if (index < listBox2.Items.Count - 1)
{
//如果index+1被選取就不進行下移
if (listBox2.SelectedIndices.Contains(index + 1))
{
continue;
}
//進行換位置的動作
object tmp = listBox2.Items[index];
listBox2.Items.RemoveAt(index);
listBox2.Items.Insert(index + 1, tmp);
listBox2.SelectedIndex = index + 1;
}
}
}
}
///
/// listbox所選項目向上移
///
private void button_up_Click(object sender, EventArgs e)
{
//檢查有沒有選取項目
if (listBox2.SelectedIndices.Count > 0)
{
//用for迴圈由小到大去巡覽
for (int i = 0; i <= listBox2.SelectedIndices.Count - 1; i++)
{
int index = listBox2.SelectedIndices[i];
//如果index為第一項就不需要上移
if (index > 0)
{
//如果index-1被選取就不進行上移
if (listBox2.SelectedIndices.Contains(index - 1))
{
continue;
}
//進行換位置的動作
object tmp = listBox2.Items[index];
listBox2.Items.RemoveAt(index);
listBox2.Items.Insert(index - 1, tmp);
listBox2.SelectedIndex = index - 1;
}
}
}
}

留言
張貼留言