Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

c# - How to add new row to datagridview only after specific cells of the row above are filled?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...