如何使用数据库检查复选框列表

how to checked checkbox list using database

我有 CheckBoxList 并想在编辑按钮上检查它。如果数据库中的列有值,它将被选中,否则不被选中。复选框列表值来自数据库。

显示错误:

Index was out of range. Must be non-negative and less than the size of the collection.

调试时:

Chk_seat.Items[j].Selected = true;

我该怎么做?

这是我的代码:

<asp:CheckBoxList ID="Chk_seat" runat="server" RepeatDirection="Horizontal">
</asp:CheckBoxList>

public void updatefields_seat(long CarID)
{
    SqlConnection cn = new SqlConnection(connection);
    string qry = @"SELECT [ID]
                ,[ReferenceID]
                ,[CarID]
                ,[Child-Seat]
                ,[Leather-Seat]
                ,[Power-Seat]
                ,[Navigation-System]
                ,[Power-Steering]
                ,[Bucket-Seat]
                ,[IsActive]
                FROM [dbo].[Seat_tbl] Where CarID=" + CarID + "";

    DataSet dsSeat = new DataSet();
    dsSeat = cm.GetQryInDataset(qry);

    if (dsSeat.Tables.Count > 0)
    {
        for (int i = 0; i < dsSeat.Tables[0].Rows.Count; i++)
        {
            for (int j = 0; j < dsSeat.Tables[0].Columns.Count; j++)
            {
                if (dsSeat.Tables[0].Rows[i]["Child-Seat"].ToString() != "")
                {
                    Chk_seat.Items[j].Selected = true;
                }
            }
        }
    }
}

dsSeat.Tables[0].Columns.Count 可能大于您的 CheckBoxList 的 size/length 这就是您收到此错误的原因:

Index was out of range. Must be non-negative and less than the size of the collection.