1

我在数据表中添加了一个复选框

初始化

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

添加复选框

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

添加这个新行

dr = dt.NewRow();

当我尝试初始化新行复选框的初始状态时发生问题

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

抛出异常说:

无法将“System.DBNull”类型的对象转换为类型 *“System.Web.UI.WebControls.CheckBox”。*

我的方法错了吗?有人可以建议如何将 DataColumn 转换回 CheckBox 吗?

4

2 回答 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);
于 2011-12-29T08:56:10.037 回答
0

DataColumn 中有什么值?听起来像是一个 NULL 值?无论如何,您不能将数据列转换为复选框。
默认情况下,复选框始终为 false,因此您不需要它。

于 2011-12-29T08:46:54.653 回答