简体   繁体   中英

Best way to auto-increment ID column in a DataGridView?

I have a dataGridView in which I can insert, delete and update values but something is bothering me. The user can only modify the 2 columns that are displayed (size and quantity), 2 others are hidden (ID and chosenComponent). ID is PK in my table.

This is what I did to set ID and chosenComponent of new rows :

private void dataGridViewStock_DefaultValueNeeded(object sender,
System.Windows.Forms.DataGridViewRowEventArgs e) 
    {
        e.Row.Cells["id"].Value = "1";
        e.Row.Cells["codeArticleComponent"].Value = labelComponentChosen.Text;
    }

Whatever value I put for the ID, the first available number will be inserted to the database. It works but I'm afraid it might later cause bugs.

Is there a better way to achieve this ? Or can I leave it as is ?

You may need a separate column(Only in the GirdView) to identify whether the current row is newly added or existing one. And increment id column with negative values based on the new column.

While saving the data you can identify the newly created rows, based on that you can save the data by inserting without id column or update the existing data.

Hope this clarifies you.

This is my code for the auto-increment primary key in a datagrid view

private void Row_Added(object sender, 
DataGridViewRowsAddedEventArgs e){
  foreach(DataGridViewRow dtr in dataGridView1.Row){
  dataGridView1.Rows[e.RowIndex-1].Cells[0].Value = 
e.RowIndex;
}
}

i used this...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM