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

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

问题描述

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



问题是当我进入新行/最后一行并输入一个单元格(甚至可以在离开单元格之前删除所有输入)datagridview自动将此行添加到绑定列表,并在下面创建一个新行。我想要的是,最后一行/新行仅在上面的行(上一个新行)被正确填充时被添加。



示例

  ID NAME PRICE ... 

1啤酒2.6

2奶酪3.3

_ _______ ____< - 空行

现在如果我点击)新行ID自动设置为3,如果我单击Beer单元格,则新的行ID为空,所有默认值为空(这将是&)的工作方式。
问题是如果点击/输入新行并输入名称的东西(即使我在离开单元格之前删除内容),新行将被添加到该行下方,这是新行。因此,这行被添加到BindingList并且是不完整的,它不应该被添加,直到所有必需的单元格被正确地填充(例如价格)。



我不知道如何去做这个。请帮助我,我是C#的新手。



谢谢你的时间和答案。

解决方案

您必须处理 RowValidating 事件并取消处理检查具体条件后的事件(验证规则)。然后,当前正在输入的行将不会被提交给DataGridView,也不会添加新的行。



例如:

  if(dgv [0,e.RowIndex] .Value == DBNull.Value)
{
dgv.Rows [e.RowIndex]。 ErrorText =您必须输入此字段的值!;

//告诉DataGridView不接受这行
e.Cancel = true;
}


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.

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.

Example

ID     NAME      PRICE    ...

1      Beer       2.6

2      Cheese      3.3

_      _______     ____      <- empty row

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).

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

Thank you for your time and answers.

解决方案

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.

For example:

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天全站免登陆