0

我有一个与某些数据源绑定的复选框,我将 valueMember 分配给了某个 id?现在已绑定检查列表框,我有另一个数据表,我需要通过它捕获每个 id,如果有的话,并且想要在检查列表框项目的值成员值中检查它,如果两者都匹配,则将检查项目。我做了以下但无法选中复选框。,你能帮我解决这个问题吗?

  private void catCmb_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (mode == "EDIT")
            {
                custOptionChkList.DataSource = cDressing.GetAllDressingDetailByCatID(14);
                custOptionChkList.DisplayMember = "Description";
                custOptionChkList.ValueMember = "CatID";
                DataTable dt = objCFreeCust.GetAllFreeCustomizationItem(currProductID, custCmb.SelectedIndex);
                foreach (var ListItem in custOptionChkList.Items)
                {
                    DataRowView drv = ListItem as DataRowView;
                    int id = Convert.ToInt16(drv["CatID"]);
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (Convert.ToInt16(dr["CustomizationId"]) == id)
                        {
                            //here i need to check the item's check box from checkedboxlist
                        }

                    }
                }
            }

        }
4

2 回答 2

2

您必须SetItemChecked使用CheckedListBox.

int index = 0; //to keep track of each item index
foreach (var ListItem in custOptionChkList.Items)
{
    DataRowView drv = ListItem as DataRowView;
    int id = Convert.ToInt16(drv["CatID"]);
    foreach (DataRow dr in dt.Rows)
    {
        if (Convert.ToInt16(dr["CustomizationId"]) == id)
        {
            custOptionChkList.SetItemChecked(index, true);  //true means set it to checked            
        }
    }

    index++;
}

或带for循环:

for (int i = 0; i < custOptionChkList.Items.Count; i++)
{
    DataRowView drv = custOptionChkList.Items[i] as DataRowView;

    int id = Convert.ToInt16(drv["CatID"]);
    foreach (DataRow dr in dt.Rows)
    {
        if (Convert.ToInt16(dr["CustomizationId"]) == id)
        {
            custOptionChkList.SetItemChecked(i, true);  //true means set it to checked
        }
    }
}
于 2013-07-30T08:27:11.220 回答
1

你好,你可以试试这个..

如果您要使用 Linq to Dataset,则使用第一种方法将数据表转换为 AsEnumerable 以使用 linq 进行查询,或者只是简单地使用数据表的 Select 方法,如第二个方法所示。

foreach (ListItem item in custOptionChkList.Items)
{
     if (dt.AsEnumerable().Any(row => row.Field<String>("CustomizationId").Equals(item.Value)))
     {
         item.Selected = true;
     }
}
                  OR
foreach (ListItem item in custOptionChkList.Items)
{
     var foundid= dt.Select("CustomizationId = '" + item.Value + "'");
     if (foundid.Length != 0)
     {
         item.Selected = true;
     }
 }
于 2013-07-30T08:55:07.990 回答