user3536676
user3536676

Reputation: 21

how to check uncheck multiple items in CheckBoxList based on DataTable value

I have CheckBoxList I want to Check multiple items based on database value here is my code

String TargetQuery = "Select RoleID from t_Et_Role_Staff_Combination where  EmployeeID='" + EmployeeID + "'";    
SqlDataAdapter adapt = new SqlDataAdapter(TargetQuery, DBcon.con);        
DataTable dtcheck = new DataTable();
adapt.Fill(dtcheck);

protected void Page_Load(object sender, EventArgs e)
{    
    for (int i = 0; i < dtcheck.Rows.Count; i++)
    {    
        CheckBoxList1.SelectedValue = dtcheck.Rows[i][0].ToString();        
    }
}

but this checked only one item( the last item) from DataTable the previous items are not selected

[based on my database value administrator and aaa should be checked but now only aaa is selected]

enter image description here

Upvotes: 0

Views: 1660

Answers (1)

Suprabhat Biswal
Suprabhat Biswal

Reputation: 3216

You need to iterate inside Checkboklist items not in datatable.

if (dtcheck != null && dtcheck.Rows.Count > 0) /* Prevents from null reference exception */
{   
    for (int i = 0; i < CheckBoxList1.Items.Count; i++)
    {
        if ( i < dtcheck.Rows.Count) /* Ensure and prevents from Index out of range exception */
        {
            bool flag = default(bool);
            Boolean.TryParse(dtcheck.Rows[i][0].ToString(), out flag);
            CheckBoxList1.Items[i].Selected = flag;
        }
    }
}

Since you have updated your post and rest of detail above mentioned code won't work in that case. As mentioned your database value is administrator but your checkboxlist text is Administrator both are different you need something like following that matches the text and ignore the case.

for (int i = 0; i < dtcheck.Rows.Count; i++)
{    
    string compareText = dtcheck.Rows[i][0].ToString();
    var vCheckBoxItem = CheckBoxList1.Items.Cast<ListItem>()
                        .FirstOrDefault(x => x.Text.Equals(compareText, StringComparison.CurrentCultureIgnoreCase));
    if (vCheckBoxItem != null)
        vCheckBoxItem.Selected = true;      
}

Upvotes: 1

Related Questions