How to access the Added by program check box

advertisements

I am developing an application in which i needed the to add filter. for that am adding checkbox programmatically because the filtering option are not predefine it depends on the value in the table to i add the checkbox as fallow

public void addCusineCheckbox()
{
            DataTable CusineList = Sql.ExecuteSelectCommand("select prod_group_id,Prod_group_name from Master_Prod_Groups");
            for (int i = 0; i < CusineList.Rows.Count; i++)
            {
                CheckBox chkCusine = new CheckBox();
                chkCusine.ID = "chk" + CusineList.Rows[i]["Prod_group_name"].ToString();
                chkCusine.Text = CusineList.Rows[i]["Prod_group_name"].ToString();
                divCusineFilter.Controls.Add(chkCusine);
            }
}

which help user to select the required field(there more other option to select) and then click on apply filter on that am try to access the that added check box as fallow

public string getCusineFilterString()
{

            string CusineID =null;
            DataTable CusineList = Sql.ExecuteSelectCommand("select prod_group_id,Prod_group_name from Master_Prod_Groups");
            for (int i = 0; i < CusineList.Rows.Count; i++)
            {
                CheckBox chk = (CheckBox)Page.FindControl("chk" + CusineList.Rows[i]["Prod_group_name"]);
                if (chk.Checked == true)
                {
                    if (i == 0)
                    {
                        CusineID = CusineList.Rows[i]["prod_group_id"].ToString();
                    }
                    else
                    {
                        CusineID = CusineID + "," + CusineList.Rows[i]["prod_group_id"].ToString();
                    }
                }
            }
            return CusineID;
}

but it gives the error that object not set to an instance.

i am not getting any idea to access to the checkbox.


There are certain limitations:

  • You cannot access any controls in ASP.net which are not added before or on Init. So you can add the controls on Page OnInit, and then it will be accessible. But you have to be careful in adding the controls, so that they are added at right place and not duplicated.

  • You should not write

    CheckBox chk = (CheckBox)Page.FindControl("chk");

instead write

var chkControl = Page.FindControl("chk");
if(chkControl != null /*&& check type*/) {
  CheckBox chk = (CheckBox)chkControl;
// and do something
}

  • It will be better if you use CheckBoxList Control at design time and change the binding values to populate different check boxes at runtime

  • Create check box(s) at design time and show hide based on user action.

Hope it helps