Reputation: 1016
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
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());
Upvotes: 3
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
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
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
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