且构网

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

仅在填写上述行的特定单元格后,如何向datagridview添加新行?

更新时间:2023-12-05 12:33:46

您必须处理 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;
}