C# 公共控制元件之ListBox
阿新 • • 發佈:2018-11-10
Winform控制元件ListBox的用法
1、如何新增listBox的值
this.listBox1.Items.Add("張曉東");
2、如何判斷listBox集合是否新增過
//檢查新增值是否新增過
if(this.listBox1.items.Contains("張曉東")){
MessageBox.show("集合成員已新增過!");
}
else{
//執行新增集合成員
}
3、如何獲取listBox選中的值
//判斷所有選中項集合大於0 if(this.listBox1.SelectedItems.Count > 0){ //獲取選中的值 this.listBox1.SelectedItem.ToString(); } else{ MessageBox.Show("未選中listbox集合的值"); }
4、如何移除listBox中存在的值
//移除listBox集合的項
this.listBox1.Items.Remove("張曉東");
5、綜合使用例子
簡單實現人員從部門1轉移到部門2或部門2轉移到部門1
1)介面設計
2)新增人員
/// <summary> /// 新增人員到採購部門 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnInsert_Click(object sender, EventArgs e) { //獲取新增人的值 string peopleText = this.txtPeople.Text.Trim().ToString(); //獲取listbox1的物件 ListBox list1 = this.listBox1; //判斷人員是否已經新增過 if (!list1.Items.Contains(peopleText)) { list1.Items.Add(peopleText); } else { MessageBox.Show("該人員已經新增過,無法重複新增!"); } }
3)轉移人員>>>
/// <summary> /// 將採購人員轉移到銷售部門 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnRightMove_Click(object sender, EventArgs e) { //獲取listbox1的所有選中的項 if (this.listBox1.SelectedItems.Count > 0) { string checkPeople = this.listBox1.SelectedItem.ToString(); //判斷是否新增到listbox2 if (!this.listBox2.Items.Contains(checkPeople)) { //新增人員到listbox2中 this.listBox2.Items.Add(checkPeople); //移除listbox1中 this.listBox1.Items.Remove(checkPeople); } else { MessageBox.Show("該人員已經轉移過,無法重複轉移!"); } } else { MessageBox.Show("未選中採購人員,無法轉移銷售部門!"); } }
4、<<<轉移人員
/// <summary>
/// 將銷售人員轉移到採購部門
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLeftMove_Click(object sender, EventArgs e)
{
//獲取listbox2的所有選中的項
if (this.listBox2.SelectedItems.Count > 0)
{
string checkPeople = this.listBox2.SelectedItem.ToString();
//判斷是否新增到listbox1
if (!this.listBox1.Items.Contains(checkPeople))
{
//新增人員到listbox1中
this.listBox1.Items.Add(checkPeople);
//移除listbox1中
this.listBox2.Items.Remove(checkPeople);
}
else
{
MessageBox.Show("該人員已經轉移過,無法重複轉移!");
}
}
else
{
MessageBox.Show("未選中銷售人員,無法轉移到採購部門!");
}
}
5、介面演示
5.1)新增人員到部門1演示效果
5.2)部門1轉移到部門2演示效果
5.3)部門2轉移到部門1演示效果