如何获取要显示的checkboxlist值

时间:2013-04-30 02:24:25

标签: c# asp.net sql checkbox

我通过以下方式绑定了我的复选框:

        string countrySQL = "Select id, CurrencyName From VirtualAccount_Currency";
        string[] param = { };
        object[] paramVal = { };

        return ClassDBQuery.ExecDataReader(countrySQL, param, paramVal);

数据层:

        string selCurrSQL = "SELECT * FROM VirtualAccount WHERE MerchantMasterID = @id";

        string[] param = { "@id" };
        object[] paramVal = { currID };

        return ClassDBQuery.ExecDataReader(selCurrSQL, param, paramVal);

这是我的代码:

            DataTable currDT = new DataTable();
            currDT = ClassView.SelectCurrency(idses);

            foreach (DataRow row in currDT.Rows)
            {
                foreach (ListItem item in currencyBox.Items)
                {
                    if (item.Value == (row["CurrencyID"].ToString()))
                    {
                        item.Selected = true;
                        break;
                    }
                }
            }

现在,当我运行我的代码时,没有遇到任何错误,但显示了复选框的值。当我调试它时,系统只在第一个foreach循环进入第二个foreach但是没有经过if语句... 我的代码出了什么问题..?

谢谢......

2 个答案:

答案 0 :(得分:1)

尝试以下,

        foreach (DataRow row in currDT.Rows)
        {
            foreach (ListItem item in currencyBox.Items)
            {
                // check here what you get
                int currencyId= row.Field<int>("CurrencyID");

                if (item.Value == currencyId.ToString())
                {
                    item.Selected = true;
                    break;
                }
            }
        }

如果您的字段CurrencyID可以具有空值,那么

int? currencyId= row.Field<int?>("CurrencyID");

if (currencyId! =null && item.Value == currencyId.ToString())
{
    item.Selected = true;
    break;
}

答案 1 :(得分:0)

试试这个: -

 for (int j = 0; j < CheckBoxList1.Items.Count; j++)
 {
 if (CheckBoxList1.Items[j].Text.Trim() ==row["CurrencyID"].ToString())
 {  
 CheckBoxList1.Items[j].Selected = true;  break;
 }
 }

希望这会有所帮助!!