ListBox控件屬性介紹:
SelectIndex:當前選中的列表項的序號。
SelectItem:當前選中的列表項。
清除列表框中全部的列表代碼:
//獲取列表框的選項數
int count = ListBox1.Items.Count; int index = 0; //循環列表框中的列表數
for (int i = 0; i < count; i++) { ListItem item = ListBox1.Items[index]; //移除列表框中的列表項
ListBox1.Items.Remove(item); } //獲取下一個選項的索引值
index++;
清除一個或多個列表的代碼:
//獲取列表框的選項數
int count = ListBox1.Items.Count; int index = 0; for (int i = 0; i < count; i++) { ListItem item = ListBox1.Items[index]; if (ListBox1.Items[index].Selected==true) //判斷當前列表框中選擇的列表項
{ ListBox1.Items.Remove(item); //移除當前列表框中選擇的列表項
index--; } index++; }
上移代碼:
//若不是第一行則上移
if (ListBox1.SelectedIndex > 0 && ListBox1.SelectedIndex <= ListBox1.Items.Count - 1) { //保存當前選項的信息
string name = ListBox1.SelectedItem.Text; string value = ListBox1.SelectedItem.Value; //獲取當前選項的索引號
int index = ListBox1.SelectedIndex; //交換當前選項與上一項的信息
ListBox1.SelectedItem.Text = ListBox1.Items[index - 1].Text; ListBox1.SelectedItem.Value = ListBox1.Items[index - 1].Value; ListBox1.Items[index - 1].Text = name; ListBox1.Items[index - 1].Value = value; //設定上一項為當前選項
ListBox1.SelectedIndex--; }
下移代碼:
//若不是最后一行則下移
if (ListBox1.SelectedIndex >= 0 && ListBox1.SelectedIndex <ListBox1.Items.Count - 1) { //保存當前選項的信息
string name = ListBox1.SelectedItem.Text; string value = ListBox1.SelectedItem.Value; //獲取當前選項的索引號
int index=ListBox1.SelectedIndex; //交換當前選項與下一項的信息
ListBox1.SelectedItem.Text = ListBox1.Items[index + 1].Text; ListBox1.SelectedItem.Value = ListBox1.Items[index + 1].Value; ListBox1.Items[index + 1].Text = name; ListBox1.Items[index + 1].Value = value; //設定下一項為當前選項
ListBox1.SelectedIndex++; }
左邊為目標列表框,右邊為源列表框。
全部左移代碼:
int count = ListBox2.Items.Count; int index = 0; for (int i = 0; i < count; i++) { ListItem item = ListBox2.Items[index]; ListBox2.Items.Remove(item); ListBox1.Items.Add(item); } index++;
單個或多個右移代碼:
int count = ListBox2.Items.Count; int index = 0; for (int i = 0; i < count; i++) { ListItem item = ListBox2.Items[index]; if (ListBox2.Items[index].Selected == true) { ListBox2.Items.Remove(item); ListBox1.Items.Add(item); index--; } index++; }