C# winform Listbox添加和删除items
两个listbox添加和删除items
1 #region 添加/移除 2 //添加 3 private void btnAdd_Click(object sender, EventArgs e) 4 { 5 if (listboxA.Items.Count <= 0) 6 { 7 return; 8 } 9 this.AddItems(listboxB, listboxA.SelectedItems); 10 this.RemoveItems(listboxA, listboxA.SelectedItems); 11 //UpdateListViewHandler();//调用委托,更新原列表 刷新MainForm窗体 12 } 13 //移除 14 private void btnRemove_Click(object sender, EventArgs e) 15 { 16 if (listboxB.Items.Count <= 0) 17 { 18 return; 19 } 20 this.AddItems(listboxA, listboxB.SelectedItems); 21 this.RemoveItems(listboxB, listboxB.SelectedItems); 22 //UpdateListViewHandler();//调用委托,更新原列表 刷新MainForm窗体 23 } 24 /// <summary> 25 /// 向一个ListBox中添加Items 26 /// </summary> 27 /// <param name="lstBox"></param> 28 /// <param name="items"></param> 29 private void AddItems(UI.ListBoxEx lstBox, IEnumerable items) 30 { 31 DataTable dt = null; 32 foreach (object item in items) 33 { 34 if (item is DataRowView) 35 dt = ((DataRowView)item).Row.Table.Clone(); 36 if (item is DataRow) 37 dt = ((DataRow)item).Table.Clone(); 38 break; 39 } 40 if (lstBox.DataSource != null) 41 dt = ((DataTable)lstBox.DataSource).Copy(); 42 foreach (object item in items) 43 { 44 if (item is DataRowView) 45 dt.Rows.Add(((DataRowView)item).Row.ItemArray); 46 if (item is DataRow) 47 dt.Rows.Add(((DataRow)item).ItemArray); 48 } 49 lstBox.DataSource = dt; 50 if (this.Text.Contains("Add or Remove Exc")) 51 { 52 lstBox.DisplayMember = "ExcName"; 53 lstBox.ValueMember = "ExcID"; 54 } 55 else if (this.Text.Contains("Add or Remove Cs")) 56 { 57 lstBox.DisplayMember = "CsName"; 58 lstBox.ValueMember = "CsID"; 59 } 60 } 61 /// <summary> 62 /// 从一个ListBox中删除Items 63 /// </summary> 64 /// <param name="lstBox"></param> 65 /// <param name="items"></param> 66 private void RemoveItems(UI.ListBoxEx lstBox, IEnumerable items) 67 { 68 DataTable dt = ((DataTable)lstBox.DataSource); 69 DataTable newDt = dt.Clone(); 70 bool flag = false; 71 //因为直接删除DataRow会保存,所以用这样丑陋的方式处理了 72 foreach (DataRow dr in dt.Rows) 73 { 74 foreach (DataRowView item in items) 75 { 76 if (dr == item.Row) 77 { 78 flag = true; 79 break; 80 } 81 else 82 flag = false; 83 } 84 if (!flag) 85 newDt.Rows.Add(dr.ItemArray); 86 else 87 continue; 88 } 89 lstBox.DataSource = newDt; 90 if (this.Text.Contains("Add or Remove Exc")) 91 { 92 lstBox.DisplayMember = "ExcName"; 93 lstBox.ValueMember = "ExcID"; 94 } 95 else if (this.Text.Contains("Add or Remove Cs")) 96 { 97 lstBox.DisplayMember = "CsName"; 98 lstBox.ValueMember = "CsID"; 99 } 100 } 101 #endregion