First, for an item contained in a listBox, assume that the listBox has duplicate data and can use this function to remove duplicate data
///<summary> // listBox has its own weighting /// </summary> /// <param name="listBox">Weight Removal Required ListBox</param> /// public void Self_Move_Repeat(ListBox listBox) { for(int i = 0; i < listBox.Items.Count; i++) { for(int j=i+1;j< listBox.Items.Count; j++) { if (listBox.Items[i].Equals(listBox.Items[j])) listBox.Items.Remove(listBox.Items[j]); } } }
The second is to compare the data you want to insert with the data inside the listBox. If there is one, do not insert it. Note here that you need to determine if the content inside the listBox is empty or eles if it is empty to insert it directly.Otherwise, an error will occur because there are no items in the listBoxListBox.ItemsThe logic of [0] is nonexistent, not empty.
public void Add_Move_Repeat(string str,ListBox listBox) { //MessageBox.Show(listBox.Items[i].ToString()); if (listBox.Items.Count > 0) { int i = 0; for (; i < listBox.Items.Count; i++) { if (listBox.Items[i].ToString().Equals(str)) { break; } } if(i==listBox.Items.Count) listBox.Items.Add(str); } else { listBox.Items.Add(str); } }
Here we put the two de-duplication schemes in a ListBox_Within the Oprate class, when used, a new outgoing parameter can be used
ListBox_Oprate listBox_Oprate=new ListBox_Oprate; listBox_Oprate. Self_Move_Repeat(listBox); //ListBox is the name of the listBox to be de-duplicated listBox_Oprate. Self_Move_RepeatAdd_Move_Repeat(string str, listBox);//str is the string to add, listBox is the name of the Box to add
Attach the entire class package, remember to apply usingSystem.Windows.Controls; otherwise you cannot add a ListBox parameter
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace management system { class ListBox_Oprate { /// <summary> /// listBox I already have an item to weigh /// </summary> /// <param name="listBox">Weight Removal Required ListBox</param> /// public void Self_Move_Repeat(ListBox listBox) { for(int i = 0; i < listBox.Items.Count; i++) { for(int j=i+1;j< listBox.Items.Count; j++) { if (listBox.Items[i].Equals(listBox.Items[j])) listBox.Items.Remove(listBox.Items[j]); } } } /// <summary> /// listBox Existing but not joined listBox /// </summary> /// <param name="str"></param> /// <param name="listBox"></param> public void Add_Move_Repeat(string str,ListBox listBox) { //MessageBox.Show(listBox.Items[i].ToString()); if (listBox.Items.Count > 0) { int i = 0; for (; i < listBox.Items.Count; i++) { if (listBox.Items[i].ToString().Equals(str)) { break; } } if(i==listBox.Items.Count) listBox.Items.Add(str); } else { listBox.Items.Add(str); } } } }