繁体   English   中英

带有选中默认值的复选框的 DataGridView

[英]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)

在网格中加载值期间或之后,要检查网格中的值,请使用此代码并设置网格列的属性

foreach (DataGridViewRow row in dataGridView.Rows)
{
    row.Cells[0].Value = 1;
}

在此处输入图像描述

查看表格格式的 .xsd 文件中的属性:

表行属性

然后确保将默认值设置为合理的值:

设置默认数据列属性值

然后它会自动将默认值设置为绑定源。

一种简单的方法是使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM