Skip to main content
 首页 » 编程设计

c#之CheckBoxList 绑定(bind)需要第二个集合来确定选中状态

2024年02月24日37txw1958

我有一种情况需要将字符串数组数据绑定(bind)到 CheckBoxList。是否应检查每个项目的决定需要使用不同的字符串数组来完成。这是一个代码示例:

string[] supportedTransports = ... ;// "sms,tcp,http,direct" 
string[] transports = ... ; // subset of the above, i.e. "sms,http" 
// bind supportedTransports to the CheckBoxList 
TransportsCheckBoxList.DataSource = supportedTransports; 
TransportsCheckBoxList.DataBind(); 

这很好地绑定(bind),但每个项目都未选中。我需要以某种方式查询 transports 以确定检查状态。我想知道是否有一种简单的方法可以使用 CheckBoxList 执行此操作,或者我是否必须创建某种适配器并绑定(bind)到它?

提前致谢!

请您参考如下方法:

您可以为此使用一些 LINQ:

        string[] supportedTransports = { "sms", "tcp", "http", "direct" }; 
        string[] transports = { "sms", "http" };  
 
        CheckBoxList1.DataSource = supportedTransports; 
        CheckBoxList1.DataBind(); 
 
        foreach (ListItem item in CheckBoxList1.Items) 
        { 
            if (transports.Contains(item.Text)) 
            { 
                item.Selected = true; 
            } 
        }