[英]How to add a checkbox control to a datatable?
How can i add a checkbox to a datatable and bind it to a datagrid? 如何在数据表中添加复选框并将其绑定到数据网格?
DataTable ColumnList = new DataTable();
ColumnList.Columns.Add("Column Fields");
int j = 1, i = 0;
CheckBox colCheckbox = new CheckBox();
foreach (Columns col in ColumnNames)
{
colCheckbox.Name = col.ColumnName;
ColumnList.Rows.Add(colCheckbox); // This is getting displayed as System.Windows.Forms.CheckBox,CheckState=0
}
Please help. 请帮忙。
You'll have to have a boolean
field (column) in the DataTable. 你必须在DataTable中有一个
boolean
字段(列)。 When you bind the DataTable to the DataGridView, a checkbox column will be created for that boolean
field. 将DataTable绑定到DataGridView时,将为该
boolean
字段创建一个复选框列。
Sample Code: 示例代码:
var dt = new DataTable();
dt.Columns.Add(new DataColumn("Selected", typeof(bool))); //this will show checkboxes
dt.Columns.Add(new DataColumn("Text", typeof(string))); //this will show text
var dgv = new DataGridView();
dgv.DataSource = dt;
This will bind the dt
DataTable to the dgv
DataGridView. 这会将
dt
DataTable绑定到dgv
DataGridView。 The DataGridView will automatically display a DataGridViewCheckBoxColumn for the first DataColumn ( Selected ) and a DataGridViewTextBoxColumn for the second DataColumn ( Text ). 在DataGridView将自动显示一个DataGridViewCheckBoxColumn用于第一的DataColumn( 选择的 )和DataGridViewTextBoxColumn用于第二的DataColumn( 文本 )。
You have to specify the type of the column. 您必须指定列的类型。
ColumnList.Columns.Add("Column Fields", gettype(CheckBox));
But why do you want to add a control to a DataTable? 但是为什么要将控件添加到DataTable? Why not just a string or an integer?
为什么不只是一个字符串或整数?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.