且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在向DataGridView添加新行时进行预填充

更新时间:2023-11-30 22:07:46

尝试使用 ^ ]方法!


这将对具有三列的未绑定网格执行此操作
响应按钮单击或其他一些事件,其中
用户尚未将行直接添加到网格中

This will do it for an unbound grid with three columns
in repsonse to a button click or some other event where
the user has not added the row directly to the grid

private void addRowButton_Click(object sender, EventArgs e)
{
    int rowIndex = dataGridView1.Rows.Add();
    DataGridViewRow row = dataGridView1.Rows[rowIndex];
    row.Cells[0].Value = "test1";
    row.Cells[1].Value = "test2";
    row.Cells[2].Value = "test3";
    dataGridView1.CurrentCell = row.Cells[0];
}



当用户确实通过输入
将一行添加到网格中时 新行行的其中一列中的数据
以下将起作用



When the user does add a row to the grid by entering
data in one of the columns on the new row line the
following will work

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    DataGridViewRow row = dataGridView1.Rows[e.RowIndex - 1];
    row.Cells[0].Value = "test1";
    row.Cells[1].Value = "test2";
    row.Cells[2].Value = "test3";
}



请注意,任何用户输入都将覆盖此处设置的值.通过设置
可以避免这种情况 列只能在需要的地方读取.



Note that any user input will override values set here. This can be avoided by making
columns read only where required.


我遇到了同样的问题:如何将DataGrid的空白行放入
具有计算值.我张贴了问题,并在这里回答:

http://***.com/questions/12485664/set-the- content-of-a-new-row-datagrid [ ^ ]

我在这里复制答案:

当将DataTable绑定到DataGrid时,将创建CollectionView以便查看它.您可以使用(静态/共享)CollectionView.GetDefaultView(ThePropertyThatIsBound)方法获取它.
由于它实现了ICollectionChanged,因此可以将事件处理程序添加到CollectionChangedEvent.

在CollectionChanged事件处理程序中,如果有新项目(e.NewItems.Count> 0),则必须对照System.Windows.Data.CollectionView.NewItemPlaceholder进行检查,如果它不是占位符,则它是全新的项目,为了我可以设置所有默认值.
I had same issue : how to have the blank row of the DataGrid to
have computed values. I posted the question, and answer here :

http://***.com/questions/12485664/set-the-content-of-a-new-row-datagrid[^]

i copy the answer here :

When a DataTable is bound to a DataGrid, a CollectionView is created in order to see it. You can get it by using the (static/shared) CollectionView.GetDefaultView(ThePropertyThatIsBound) method.
Since it implements ICollectionChanged, you can add an event handler to the CollectionChangedEvent.

In the CollectionChanged event handler, if you have a new item (e.NewItems.Count>0) you must check it against System.Windows.Data.CollectionView.NewItemPlaceholder and if it is not a place holder, then it is a brand new item, for wich i can set all default values.