如何仅在填充上面行的特定单元格后向 datagridview 添加新行? [英] How to add new row to datagridview only after specific cells of the row above are filled?

查看:18
本文介绍了如何仅在填充上面行的特定单元格后向 datagridview 添加新行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C# (.NET 4.0) 开发桌面应用程序.我有一个填充自定义对象的 datagridview,通过自定义(它继承了 BindingList)BindingList(添加了排序功能).我使用 cellValidating 事件来正确增加第一列 (ID) 并验证对其他单元格的输入.

I'm working on a desktop application in C# (.NET 4.0). I have a datagridview filled with custom objects, via custom (it inherits BindingList) BindingList (added sorting functionalities). I use cellValidating events to properly increment first column (ID) and to validate input into other cells.

问题是当我到达新行/最后一行并在一个单元格中输入一些内容(我什至可以在离开单元格之前删除所有输入)时,datagridview 会自动将此行添加到绑定列表并在下方创建一个新行.我希望只有在正确填充上面的行(前一个新行)时才添加最后一行/新行.

The problem is when I get to the new row / last row and enter something into one cell (I can even delete all the input before leaving the cell) the datagridview automatically adds this row to binding list and creates a new row below. I want that the last / new row is only added when the row above (previous new row) is properly filled.

示例

ID     NAME      PRICE    ...

1      Beer       2.6

2      Cheese      3.3

_      _______     ____      <- empty row

现在,如果我单击(输入)新行 ID 会自动设置为 3,如果我将单击保留到啤酒"单元格,则新行 ID 为空且所有默认值都为空(这是应该的方式)确实有效).问题是,如果单击/输入新行并为名称键入一些内容(即使我在离开单元格之前删除了内容),则会在该行下方添加一个新行,即新行.因此,这一行被添加到 BindingList 并且是不完整的,在正确填充所有必需的单元格之前不应添加它(例如价格).

Now if I click (enter) the new row ID is automatically set to 3 and if I leave click to 'Beer' cell, new row ID is empty and all default values are empty (which is the way it should & does work). The problem is if if click / enter new row and type something for name (and even if I delete the content before leaving cell) a new row is added below this row, which was new row. Thus this row is added to BindingList and is incomplete, it shouldn't be added until all required cells are properly filled (for instance price).

我不知道该怎么做.请帮帮我,我对 C# 很陌生.

I have no idea how to do this. Please help me out, I'm quite new to C#.

感谢您的时间和回答.

推荐答案

必须处理RowValidating事件,并在检查特定条件后取消对事件的处理(验证规则).然后,当前输入的行将不会提交到 DataGridView,也不会添加新行.

You have to handle the RowValidating event and cancel the handling of the event after checking specific conditions (validation rules). Then, the currently being entered row will not be committed to the DataGridView and no new row will be added.

例如:

if (dgv[0, e.RowIndex].Value == DBNull.Value)
{
    dgv.Rows[e.RowIndex].ErrorText = "You must enter a value for this field!";

    // Tell the DataGridView not to accept this row
    e.Cancel = true;
}

这篇关于如何仅在填充上面行的特定单元格后向 datagridview 添加新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆