1

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?

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Can you suggest me some snippets or workaround to actually do it?
I had run this code on my machine and was working fine. Paste your code.
0

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.

1 Comment

I also need the casting to figure whether the CheckBox.Checked is TRUE or FALSE, not only to do the initialization. And when I tried, the same exception was thrown. Yes since the value is NULL therefore I need to initialize the value....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.