Mark
Mark

Reputation: 2760

How to check a value in check box after databinding

I am doing a data bind to a check box, So I display 6 values in my check box, and users are given 2 random values when they are created. How can I check the values in the check box after I do the databind. If value 2 and 4 are give for a user then the check box should display 1 to 6 which I am doing using databind and I have to check 2 and 4 value how can I do that

 while (reader.Read())
        {
            rolegiven.Add(reader["RoleName"].ToString());
        }
        reader.Close();
        if (rolegiven.Any(item => item.Equals("Value1")))
        {
            ckl_EditRole.SelectedIndex = 0;
        }else{}
        if (rolegiven.Any(item => item.Equals("Value2")))
        {
            ckl_EditRole.SelectedIndex = 1;
        }else{}
        if (rolegiven.Any(item => item.Equals("Value3")))
        {
            ckl_EditRole.SelectedIndex = 2;
        }else{}

If value 2 and 3 are selected( from Databinding I find that value2 and value 3 are given for the user) only value 3 is checked. How can I do this

Upvotes: 0

Views: 534

Answers (1)

KV Prajapati
KV Prajapati

Reputation: 94643

You have to use Items collection of CheckBoxList control.

List<string> rolegiven = new List<string>()
    {
         "A","B","C","D","E","F"
    };
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CheckBoxList1.DataSource = rolegiven;
            CheckBoxList1.DataBind();

            CheckBoxList1.Items[0].Selected = true;
            CheckBoxList1.Items[2].Selected = true;
            CheckBoxList1.Items[4].Selected = true;

            //or

            if(rolegiven.Any(item => item.Equals("A")))
              CheckBoxList1.Items[0].Selected = true;
            if(rolegiven.Any(item => item.Equals("D")))
              CheckBoxList1.Items[3].Selected = true;
            ...
        }
    }

Upvotes: 1

Related Questions