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?

有帮助吗?

解决方案

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);

其他提示

What value is in the DataColumn? Sounds like it's a NULL value? And anyway, you cannot cast a datacolum to a Checkbox.
A checkbox is always false by default, so you don't need that.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top