C#将Combobox中的项目添加到列表框中,不重复 [英] C# Add items from Combobox to listbox without duplicate

查看:116
本文介绍了C#将Combobox中的项目添加到列表框中,不重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI朋友,Iamin是一个大问题,并且在没有找到我的问题的解决方案的情况下坚持了3天,请让我知道以下查询的解决方案请给我发电子邮件删除电子邮件



我在combobox 4中有一个软件列表,在表单加载时,列表中会列出一个软件列表,所以在更新时如果我点击了combobox4中的软件列表,它会在列表框中重复,问题是我不能交叉检查所选的组合框值已经在列表中。列表框使用逗号分隔输入数据库,在列表框中列出时,它会被拆分并显示为两个不同的值。



HI Friends,Iamin a big problem and stuck for3 days without finding a solution for my issue,please let me know a solution for the below query please email me removed email

I have a list of software in combobox 4 and while form load a list of software will be listed in listbox1,so while updating if i click on the software list in combobox4 its getting duplicated in the listbox,the issue is that i cant cross check wether the selected combobox values are already in the list.The listbox is entered in to the database using comma seperation and while listing in the listbox it gets split and shows as two different values.

private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox4.Text != "")
    {
        string sc = comboBox4.SelectedItem.ToString();

        listBox1.Items.Remove("");
        listBox1.Items.Add(comboBox4.SelectedItem);
        listBox1.Items.Remove("");
        comboBox4.Items.Remove(comboBox4.SelectedItem);
    }
}




private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string li = listBox1.Text;
            comboBox4.Items.Remove("");
            comboBox4.Items.Add(li);
            comboBox4.Items.Remove("");
            listBox1.Items.Remove("");
            listBox1.Items.Remove(listBox1.SelectedItem);
         }



// Listbox1的值


//values for Listbox1

obj.cn.Open();
SqlCommand cmd2 = new SqlCommand("Select software from specs where mfcitno='" + label2.Text + "'", obj.cn);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
    ard = dr2["software"].ToString();
}
dr2.Close();
obj.cn.Close();
if (ard != null)
{
    string sofaa1 = ard.ToString();
    string[] arr1 = sofaa1.Split(',');
    foreach (string item in arr1)
    {
        listBox1.Items.Add(item);
    }
 }

推荐答案

所以问题是项目从组合框移动到列表框可能是列表框中已有的项目的副本。 (对吗?)

你需要跟踪列表框中已经存在的项目,与数据库无关。

So the problem is that items moved from the combobox to the listbox may be duplicates of items already in the listbox. (Right?)
You need to keep track of which items are already in the listbox, independent of the database.
// Add class field:
private HashSet<string> SelectedSoftware = new HashSet<string>();

// ... initialize the listbox
obj.cn.Open();
using (SqlCommand cmd2 = new SqlCommand("Select software from specs where mfcitno='" + label2.Text + "'", obj.cn))
{
  using (SqlDataReader dr2 = cmd2.ExecuteReader())
  {
    while (dr2.Read())
    {
      ard = dr2["software"].ToString();
    }
  }
}
obj.cn.Close();
// ard *should* be declared as string
if (ard != null)
{
  //line below is unnecessary, ard already is string from .ToString() above
  //string sofaa1 = ard.ToString(); 
  string[] arr1 = ard.Split(',');
  foreach (string item in arr1)
  {
    listBox1.Items.Add(item);
    SelectedSoftware.Add(item);
  }
}



然后从组合框中选择时,检查项目是否已经在 SelectedSoftware ,如果是这样,请不要再添加它。并保持 SelectedSoftware 更新:


Then when selecting from the combobox, check if the item is already in SelectedSoftware, and if so, don't add it again. And keep SelectedSoftware updated:

private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
  if (!string.IsNullOrEmpty(comboBox4.Text))
  {
    string sc = comboBox4.SelectedItem.ToString();
    if (!SelectedSoftware.Contains(sc))
    {
      //listBox1.Items.Remove("");  // WHY?
      listBox1.Items.Add(sc);
      SelectedSoftware.Add(sc);
      //listBox1.Items.Remove("");  // WHY?
      comboBox4.Items.Remove(comboBox4.SelectedItem);
    }
  }
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
  string li = listBox1.Text;
  //comboBox4.Items.Remove("");  // WHY?
  comboBox4.Items.Add(li);
  //comboBox4.Items.Remove("");  // WHY?
  //listBox1.Items.Remove("");   // WHY?
  listBox1.Items.Remove(li);
  SelectedSoftware.Remove(li);
}





如果可能的话,更好的方法是从组合框中删除列表框中已有的元素,加载列表框后,如果它们已经存在,则无法将它们添加到列表框中。 (想象一下列表框最初为空并且组合框具有所有可能的选择的情况。在组合框或列表框中的选择序列中的任何点处,所有可能的选择都在一个或另一个控件中。这是什么你的代码已经完成,它只是不会那样开始。)如果用户可以在组合框中输入新值,那么你需要确保它不是重复的,如上面。



最后,从您的代码中可以看出,只需更改列表框中的选定项目和组合框就会导致项目从一个项目移动到另一个项目。使用一对按钮将所选项目从一个列表移动到另一个列表似乎是一种更好的用户体验。



Even better, if possible, would be to remove from the combobox the elements that are already in the listbox, as soon as the listbox is loaded, so they cannot be added to the listbox if they are already there. (Imagine the case where the listbox is initially empty and the combobox has all of the possible selections. At any point in the sequence of selections from the combobox or listbox, all of the possible selections are in one or the other control. This is what your code already does, it just doesn't start out that way.) If the user can enter a new value in the combobox, then you'll need to ensure it isn't a duplicate, as above.

Finally, from your code it appears that simply changing the selected items in the listbox and combobox causes the items to be moved from one to the other. It seems like a better user experience to have a pair of buttons that move the selected items from one list to the other.


我自己解决了这个问题,只是选择了包含。在此之前我们应该确保在修剪到数组时没有空间。



请使用此代码来修改逗号分隔的字符串以形成数组。



I solved this myself just taking an option of contain.Before that we should make sure that there is no space while trimming down to an array.

Please use this code for triming a comma seperated string to form an array.

string[] spli = Regex.Split(soft1.Trim(), @"\s*[,]\s*");



这会将字符串拆分为数组后从字符串中删除空格。




this will remove the space from string after splitting it to an array.

if (!listBox1.Items.Contains(searchst))
               {

do the coding here
}


为什么不使用 FindString [ ^ ]





来自上述指定链接的示例代码。



Why don't you use FindString[^] before inserting the item?


Sample code from the above specified link.

private void FindAllOfMyString(string searchString)
{
   // Set the SelectionMode property of the ListBox to select multiple items.
   listBox1.SelectionMode = SelectionMode.MultiExtended;

   // Set our intial index variable to -1.
   int x =-1;
   // If the search string is empty exit.
   if (searchString.Length != 0)
   {
      // Loop through and find each item that matches the search string.
      do
      {
         // Retrieve the item based on the previous index found. Starts with -1 which searches start.
         x = listBox1.FindString(searchString, x);
         // If no item is found that matches exit.
         if (x != -1)
         {
            // Since the FindString loops infinitely, determine if we found first item again and exit.
            if (listBox1.SelectedIndices.Count > 0)
            {
               if(x == listBox1.SelectedIndices[0])
                  return;
            }
            // Select the item in the ListBox once it is found.
            listBox1.SetSelected(x,true);
         }

      }while(x != -1);
   }
}


这篇关于C#将Combobox中的项目添加到列表框中,不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆