ASP.NET CheckBox in DataTable

rofans91 picture rofans91 · Dec 29, 2011 · Viewed 8k times · Source

I added a checkbox into my datatable

Initialization

 DataTable dt = new DataTable();
 DataRow dr = null;

Adding the checkbox

dt.Columns.Add(new DataColumn("CheckBoxCol", typeof(CheckBox)));

Add this new row

dr = dt.NewRow();

Problem happen when I try to initialize initial state of the checkbox of the new row

((CheckBox)dr["CheckBoxCol"]).Checked = false;

There was exception thrown that says:

Unable to cast object of type 'System.DBNull' to type *'System.Web.UI.WebControls.CheckBox'.*

Is my method wrong? Can someone advice how to cast back the DataColumn back to be CheckBox?

Answer

Anand picture Anand · Dec 29, 2011

Why do you want to add check box to a datatable ? If you want to store some value, which would be used to populate a CheckBox, then suggest you to store values as Bool.

Even if you want to store the checkBox in datacolumn, then you have to do it like this

 DataTable dt = new DataTable();
 dt.Columns.Add(new DataColumn("Check", typeof(System.Web.UI.WebControls.CheckBox)));
 DataRow dr = dt.NewRow();
 CheckBox ck = new CheckBox();
 ck.Checked = true;
 dr["Check"] = ck;
 dt.Rows.Add(dr);

Since column would store reference type, then first you have to create an instance of it, set its value and then store it in the DataColumn.

If you are simply using OneColumn DataTable. I would suggest you to use List<CheckBox> which would make more sense.

 List<CheckBox> checkBoxList = new List<CheckBox>();
        CheckBox ck = new CheckBox();
        ck.Checked = true;
        checkBoxList.Add(ck);