How to add a new row in a datagridview only after filling in certain cells of the row above?

I am working on a desktop application in C # (.NET 4.0). I have a datagridview populated with user objects via custom (it inherits a BindingList) BindingList (adds sorting functions). I use cellValidating events to correctly increase the first column (ID) and check input to other cells.

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

Example

ID     NAME      PRICE    ...

1      Beer       2.6

2      Cheese      3.3

_      _______     ____      <- empty row

Now, if I press (enter), the new line identifier will be automatically set to 3, and if I leave a click on the Beer cell, the new line identifier is empty, and all default values ​​are empty (which should be done Work). The problem is that if you click / enter a new line and enter something for the name (and even if I delete the contents before leaving the cell), a new line will be added below this line, which was a new line. Thus, this line is added to the BindingList and is incomplete, it should not be added until all the necessary cells are correctly filled (for example, price).

I do not know how to do that. Please help me, I'm new to C #.

Thanks for your time and answers.

+3
source share
2 answers

RowValidating ( ). DataGridView, .

:

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

Windows DataGridView, #, :

if(txtNAME.Text.Trim()!=String.Empty&&txtPRICE.Text.Trim()!=String.Empty)
{
  MessageBox.Show("Invalid type of input","Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

else
{
  SqlConnection _sqlconnectionOne=new SqlConnection(*DatabaseConnectionString*);

  SqlCommand _sqlcommandOne=new SqlCommand();

  _sqlcommandOne.CommandType=CommandType.Text;
  _sqlcommandOne.CommandText="*INSERTStatement*";
  _sqlcommandOne.Connection=_sqlconnectionOne;
  _sqlcommandOne.ExecuteNonQuery();

  SqlConnection _sqlconnectionSecond=new SqlConnection(*DatabaseConnectionString*);

  SqlCommand _sqlcommandSecond=new SqlCommand();

  _sqlcommandSecond.CommandType=CommandType.Text;
  _sqlcommandSecond.CommandText="*SELECT*Statement*";
  _sqlcommandSecond.Connection=_sqlconnectionSecond;

  SqlDataAdapter _sqldataadapter=new SqlDataAdapter(_sqlcommandSecond);

  DataTable _datatable=new DataTable();

  _sqldataadapter.fill(_datatable);
  *DataGridViewName*.DataSource=_datatable;
}

"" , . !

0

Source: https://habr.com/ru/post/1794902/


All Articles