Search code examples
c#sqlwpfauto-generate

How do I auto-generate an ID in my WPF DataGrid when entering in new fields


What I want to do is when the person goes to enter in a new data to create a new row in the database / DataGrid. I want the ID to be auto generated. I do not want the users to be putting in their own ID. Except, I don't really have any idea of how to do this.

I have tried researching on how to do this, and have had no luck at all.

This is what I have for adding the rows into the DataGrid and database.

private void addRows_Click(object sender, RoutedEventArgs e)
{
    SqlConnection conn = new SqlConnection(sqlstring);
    conn.Open();
    string Query = "Insert into [ASSIGNMENT] ([AssignmentID], [Description], [TotalPoints], [PointsEarned], [GradeBucketID]) Values('" + this.txtAssignment.Text + "','" + txtDescription.Text + "','" + txtTotalPoints.Text + "','" + txtPointsEarned.Text + "', '" + txtGradeBucket.Text + "')";
    SqlCommand createCommand = new SqlCommand(Query, conn);
    createCommand.ExecuteNonQuery();
    MessageBox.Show("Updated");
    conn.Close();
}

Note: This is WPF and a DataGrid. Not WinForm and DataGridView. There is a difference.

Any help with this will be greatly appreciated! Thanks!


Solution

  • the best way is to configure you table in database to auto generate the key I mean Identity and not insert any value for unique column and let the table to auto generate it