Click here to Skip to main content
15,889,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a formview with a checkboxlist in edititemtemplate. I want to preselect the items that are in a datatable. How do I do this

What I have tried:

I have tried setting the checkboxlist items to the datatable in the code behind but I cant find the control.
Posted
Updated 30-Jul-18 10:44am

You can try the rowdatabound event to find the control as shown below:

protected void formview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        Checkboxlist ck= e.Row.FindControl("id_of_checkboxlist") as checkboxlist;
    }
}
 
Share this answer
 
If your database stores a flag to determine the selected CheckBox items, then you could simply do something like:

C#
for (int i = 0; i < CheckBoxList1.Items.Count; i++){
             CheckBoxList1.Items[i].Selected = Convert.ToBoolean(dt.Rows[i]["IsSelected"]);
}


IsSelected as boolean flag from your database.

Here's a quick example:

C#
protected void FormView1_DataBound(object sender, EventArgs e)
{
        //Check for its current mode
        if (FormView1.CurrentMode == FormViewMode.ReadOnly)
        {
            //Check the RowType to where the Control is placed
            if (FormView1.Row.RowType == DataControlRowType.DataRow)
            {
                //Just Changed the index of cells based on your requirement
                CheckBoxList cal = (CheckBoxList)FormView1.Row.Cells[0].FindControl("YourCheckBoxControlIDHere");
                if (cbl= !null)
                {
                    DataTable dt = ???; //Set the datasource

                    //loop thru the items of checkboxlist and then preselect 
                    for (int i = 0; i < cbl.Items.Count; i++){
             cbl.Items[i].Selected = Convert.ToBoolean(dt.Rows[i]["IsSelected"]);
}
                }


            }
        }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900