最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】C#中ComboBox动态绑定赋值

C# crifan 6936浏览 0评论

【问题】

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中就可以看到对应的选项了:

combobox dynamic binding ok

 

【总结】

绑定的动作,其实很简单:

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

那么结果就错了,然后每一项,就都是对应的对象的名字了:

binding not ok all is obj name

具体根本原因,暂时懒得去深究了。

转载请注明:在路上 » 【已解决】C#中ComboBox动态绑定赋值

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.194 seconds, using 22.12MB memory