Ravinder Gangadher
Ravinder Gangadher

Reputation: 1016

allow only distinct values in ComboBox

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?

Upvotes: 5

Views: 23050

Answers (5)

Johan Larsson
Johan Larsson

Reputation: 17580

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.

Upvotes: 3

Kapil Khandelwal
Kapil Khandelwal

Reputation: 16144

Get Distict values in Datatable & then fill the combo:

DataView dvw = new DataView(ds.Tables[0]);
DataTable table = dvw.ToTable(true, value);

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

Upvotes: 0

Prabhu Murthy
Prabhu Murthy

Reputation: 9261

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);
     }
}

Upvotes: 7

sohel khalifa
sohel khalifa

Reputation: 5578

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;
         }
    }
}

Upvotes: 1

peroija
peroija

Reputation: 1982

you can still bind a dataset. after you bind it add the select item to the combobox at the index position you want

Upvotes: 0

Related Questions