[英]DataGridView with a checkbox with default value checked
我在 Winform 中有一个 dataGridView,我使用我在此处看到的代码向数据网格添加了一个带有复选框的列:
DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn();
{
column.HeaderText = "Export";
column.Name = "Export";
column.AutoSizeMode =
DataGridViewAutoSizeColumnMode.DisplayedCells;
column.FlatStyle = FlatStyle.Standard;
column.CellTemplate = new DataGridViewCheckBoxCell(false);
column.CellTemplate.Style.BackColor = Color.White;
}
gStudyTable.Columns.Insert(0, column);
这行得通,但我希望将复选框作为我添加的默认锯进行检查:
foreach (DataGridViewRow row in gStudyTable.Rows)
{
row.Cells[0].Value = true;
}
但复选框 col 仍未选中。 我使用一个集合作为我的数据源,并在添加数据源后更改了 col 的值。
我认为没有办法在列声明中设置检查值。 在设置数据源后,您将不得不遍历行检查它(例如在 DataBindingComplete 事件中):
for (int i = 0; i < dataGridView1.Rows.Count -1; i++)
{
dataGridView1.Rows[i].Cells[0].Value = true;
}
使用您的专栏名称:
for (int i = 0; i < dataGridView1.Rows.Count -1; i++)
{
dataGridView1.Rows[i].Cells["Export"].Value = true;
}
尝试这样做:
foreach (DataGridViewRow row in dgv.Rows)
{
row.Cells[CheckBoxColumn.Name].Value = true;
}
确保在设置 DataGridViewCheckBoxCells 的值时显示您的 DataGridView:我在 TabControl 的第二个选项卡中有我的单元格,并且单元格在初始化后始终未选中。 为了解决这个问题,我不得不将单元格初始化移动到 TabControl 的 SelectedIndexChanged 事件。
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.tabControl1.SelectedIndex == 1)
{
foreach (DataGridViewRow row in this.myGridView.Rows)
{
((DataGridViewCheckBoxCell)row.Cells[0]).Value = true;
}
}
}
您可以使用数据表并在 datagridview 中创建列,然后添加行,为每行提供第一列值为“True”或“False”。
试试这个
如果 ((bool)this.dataGridView2.Rows[i].Cells[0].FormattedValue == true)
一种简单的方法是使用NewRowIndex
属性,如下所示:
dvgInvoiceItems.Rows[dvgInvoiceItems.NewRowIndex-1].Cells[5].Value = true;
dvgInvoiceItems.Rows[dvgInvoiceItems.NewRowIndex-1].Cells[6].Value = true;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.