C #: How to handle "self-references" for tables in a DataGridView?

Situation:

My database has a table in which records can refer to other records in the same table. Each record has a unique numeric identifier (auto-identifier column) and a column with a null value IDRef, which may contain the identifier of the record to be referenced.

Now, in my C # Windows Forms application, I use a DataGridView to allow the user to edit records in a table. It can add, edit or delete items. I have a typed DataSet for storing data and a corresponding TableAdapter for loading data from the database and performing updates. The DataGridView is bound to a BindingSource, which uses a typed DataSet as a data source.

For the column, IDRefI added a ComboBox column, which fills its values ​​from the same BindingSource as the DataGridView itself. This means that the ComboBox is always updated with the number of records.

Problem:

I am showing a column IDin a DataGridView. When adding new rows, clicking in the corresponding row of the DataGridView, the identifier value is automatically filled with negative values. The final value of the auto-identifier is calculated only after saving the changes to the database using the TableAdapter.

Now, when I drop out of ComboBox for a column IDRef, I can select previously existing records (e.g. 101, 102, etc.), but I can also select the records that were added after the last update of the database (e.g. -1 , -2, -3).

Now: after using the TableAdapter method Updateto save changes to the database, these negative identifiers no longer exist - I refer to nonexistent records (in my case, this leads to a foreign key constraint error).

:

  • DataSet BindingSource ComboBox
  • "", TableAdapter
  • DataSet, ComboBox.

, , , "".

"" DataGridView?

EDIT: ,

+3
2

, .

, , .

, , BindingSource ( ) combobox ( BindingSource).

, , Adapter.Update(dataRow)

+1
0

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


All Articles