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
?
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".
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.
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.
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);
}
}
You can try:
cmb.Items.Clear();
cmb.Items.Add("Select");
cmb.Items.AddRange(dds.Tables[0].AsEnumerable()
.Select(x=>x[value].ToString())
.Distinct());
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With