填充具有相同值的 DataGridView 列

Populate a column of DataGridView with same Value

我有一个包含 3 列的 Winforms DataGridView,最后一列称为 'Add'。现在我必须在上面显示的所有行中用文本 'Add' 填充该列。

现在要用相同的文本填充每一行,我只知道在整个 gridview 的行集合上使用 for 循环并分配文本。所以我想知道是否还有其他方法,通过它也可以实现,不涉及任何 for 循环。 谢谢 !

你可以这样做:

var rows = myDataGridView.Rows.Cast<DataGridViewRow>().Select( c =>
{
    c.Cells[2].Value = "Add";//3rd column
    return c;
} ).ToArray();

myDataGridView.Rows.Clear();//Clear the rows so you can re-add them with the value
myDataGridView.Rows.AddRange( rows );

Cells[2] 表示索引为 2 的列,因此在本示例中,我将用 Add.

一词填充第 3 列(已经填充的行)

您可以为该列设置默认值,如下所示 添加一个文本框列并设置如下值

dataGridView1.Columns["columnName"].DefaultCellStyle.NullValue = "Add";

如果网格是数据绑定的,请尝试将其添加到更容易的数据源中。