Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allow only distinct values in ComboBox

Tags:

c#

winforms

In my project, I'm trying to populate ComboBox from DataSet. I succeeded in populating but the values inside the ComboBox are not distinct (Because it shows the values present in DataSet). I cant bind the ComboBox to DataSet because I'm adding "Select" text at first of populating the values.

ComboBox --> cmb
DataSet --> ds
DataSet Column Name --> value(string)

Here is my code:

cmb.Items.Clear();
cmb.Items.Add("Select");
for (int intCount = 0; intCount < ds.Tables[0].Rows.Count; intCount++)
{
    cmb.Items.Add(ds.Tables[0].Rows[intCount][value].ToString());
}
cmb.SelectedIndex = 0;

How would I allow distinct values (or restrict duplicate values) inside the ComboBox?

like image 634
Ravinder Gangadher Avatar asked Nov 03 '12 10:11

Ravinder Gangadher


People also ask

How do I show only unique values in ComboBox?

Then right-click on the combo box and select Properties from the popup menu. Then click on the button (with the 3 dots) to the right of the "Row Source" property to bring up the Query Builder window. When the Query Properties window appears, set the Unique Values property to "Yes".

How do I remove items from ComboBox?

To remove an itemCall the Remove or RemoveAt method to delete items. Remove has one argument that specifies the item to remove. RemoveAt removes the item with the specified index number.

How do I make a ComboBox read only?

Just change the DropDownStyle to DropDownList . Or if you want it completely read only you can set Enabled = false , or if you don't like the look of that I sometimes have two controls, one readonly textbox and one combobox and then hide the combo and show the textbox if it should be completely readonly and vice versa.


3 Answers

for (int intCount = 0; intCount < ds.Tables[0].Rows.Count; intCount++)
{
     var val=ds.Tables[0].Rows[intCount][value].ToString();

     //check if it already exists
     if(!cmb.Items.Contains(val))
     {
            cmb.Items.Add(val);
     }
}
like image 53
Prabhu Murthy Avatar answered Sep 29 '22 17:09

Prabhu Murthy


You can try:

cmb.Items.Clear();
cmb.Items.Add("Select");
cmb.Items.AddRange(dds.Tables[0].AsEnumerable()
                           .Select(x=>x[value].ToString())
                           .Distinct());
  • It uses linq to select the values, applying Distinct() selects unique values
  • You can apply an OrderBy if you want the values to be sorted.
like image 37
Johan Larsson Avatar answered Sep 29 '22 17:09

Johan Larsson


for(int i = 0; i < cmb.Items.Count; i++)
{
    for(int y = 0; y < cmb.Items.Count; y++)
    {
         if( y != i && cmb.Items[i].Text == cmb.Items[y].Text)
         {
              cmb.Items.RemoveAt(i);
              break;
         }
    }
}
like image 24
sohel khalifa Avatar answered Sep 29 '22 18:09

sohel khalifa