data binding with combo box is not working
why this code is not working ....
I want to binding the combo box with names coming from database table like this
private void getcategories()
{
var category = (from categories in tgs.categories
select categories.category_Name).ToList();
categoryCombobox.DataSource = category;
}
private void 开发者_StackOverflow中文版categoryCombobox_SelectedIndexChanged(object sender, EventArgs e)
{
getcategories();
}
am i doing any thing wrong for binding the details to combobox any suggestions pls that would be helpful to me
you need to specify a certain column to be bind in combo box.
private void getcategories()
{
var category = (from categories in tgs.categories
select categories.category_Name).ToList();
categoryCombobox.DataSource = category;
categoryCombobox.DataBind(); //dont forget this
}
edit - just as a small general criticism, your method is named poorly. I would do something more like:
private IEnumerable<string> Getcategories()
{
return categproes.Select(c=>c.category_Name);
}
private void BindCategories()
{
categoryCombobox.DataSource = this.GetCategories();
categoryCombobox.DataBind();
}
private void categoryCombobox_SelectedIndexChanged(object sender, EventArgs e)
{
BindCategories();
}
You are binding it in the Selected Index changed event of the same combobox, which will not fire unless you have some items in the combobox.
Try the code in getcategories() somewhere else like form_load or on a button click and remove it from the handler
You don't want to set the datasource every time the index changes, just the once in the FormLoad
, event for example. Otherwise it will never be initially set, and may cause an infinite loop when the index does change, as it will reset the datasource, changing the index, which will reset the datasource etc..
Try changing it to this:
private void Form_Load(object sender, EventArgs e)
{
LoadCategoriesCombo();
}
private void LoadCategoriesCombo()
{
var category = (from categories in tgs.categories
elect categories.category_Name).ToList();
categoryCombobox.DataSource = category;
}
精彩评论