http://www.crifan.com/csharp_combobox_data_dynamic_binding/
C#中,已有一个List,想要动态的,绑定到ComboBox中。
【解决过程】
1.参考:
c# winform comboBox动态绑定数据
去试试代码:
cmbSubCategory.DataSource = generalCategoryList;
cmbSubCategory.DisplayMember = "name";
cmbSubCategory.ValueMember = "url";
结果是可以执行,但是点击combobox时,下来菜单是空的。
2.参考:
C# Binding Generic LIst<string> to Combo Box
打算去试试。
3.经过后来的折腾,找到原因了:
【已搞懂】C#中代码加了断点,但是调试时却无法执行到
4.然后此处,实际上是,之前的写法,就是正常的:
public struct categoryItem
{
public string Name { get; set; }
public string Url { get; set; }
};
List<categoryItem> generalCategoryList;
private void initSearchCategory()
{
generalCategoryList = new List<categoryItem>();
foreach (HtmlNode singleOptionNode in optionNodeList)
{
......
//store info
categoryItem singleCategoryItem = new categoryItem();
singleCategoryItem.Name = generalCategory;
singleCategoryItem.Url = singleCategoryUrl;
//add to list
generalCategoryList.Add(singleCategoryItem);
}
if (generalCategoryList.Count > 0)
{
//init search category
cmbSubCategory.DataSource = generalCategoryList;
cmbSubCategory.DisplayMember = "name";
cmbSubCategory.ValueMember = "url";
}
}
然后ComboBox中就可以看到对应的选项了:
【总结】
绑定的动作,其实很简单:
cmbSubCategory.DataSource = generalCategoryList;
cmbSubCategory.DisplayMember = "name";
cmbSubCategory.ValueMember = "url";
就可以了。
但是要注意:
此处,如果改为:
public struct categoryItem
{
public string name;
public string url;
};
List<categoryItem> generalCategoryList;
private void initSearchCategory()
{
generalCategoryList = new List<categoryItem>();
foreach (HtmlNode singleOptionNode in optionNodeList)
{
......
//store info
singleCategoryItem.name = generalCategory;
singleCategoryItem.url = singleCategoryUrl;
//add to list
generalCategoryList.Add(singleCategoryItem);
}
if (generalCategoryList.Count > 0)
{
//init search category
cmbSubCategory.DataSource = generalCategoryList;
cmbSubCategory.DisplayMember = "name";
cmbSubCategory.ValueMember = "url";
}
}
那么结果就错了,然后每一项,就都是对应的对象的名字了:
具体根本原因,暂时懒得去深究了。