I’m using a datagridview to display the records of a database. I also have a form that collects new data to be added to the database too. What I want to know is if the primary key is generated automatically or not once the data is inserted in the database using dataAdapter-DataSets.
I have a method in a class that handles all the tables for the different datagridviews. The client method looks like this.
public void AddNewClient (Client client)
{
try
{
DataRow dr = dataSet.Tables["Clients"].NewRow ();
dr[1] = client.firstName;
dr[2] = client.lastName;
dr[3] = client.MI;
dr[4] = client.address;
dr[5] = client.city;
dr[6] = client.state;
dr[7] = client.zipcode;
dr[8] = client.homePhone;
dr[9] = client.cellPhone;
dr[10] = client.otherPhone;
dr[11] = client.faxNumber;
dr[12] = client.email;
dataSet.Tables["Clients"].Rows.Add (dr);
adapterClients.Update (dataSet, "Clients");
}
catch (Exception e) { throw e; }
}
The dataSet.Tables[“Clients”] is bind to the DataGridViewClients. When the new record displays in the DataGridViewClients there’s no ClientID value. However, when I restart the application and the DataGridViewClients is displayed I can see how a new value to ClientID has been assigned. So I wonder is this something that is done automatically by SQL server or ….? I mean I don’t really know. 🙂
The ClientID is probably an identity column. That means the database automatically assigns a new number to each row. Even if you wanted to, you would not be allowed to set the value of the identity column yourself.
An identity column is often a primary key, but this is not always true. A primary key can be made up of any set of columns that uniquely identifies a row. It’s easy to see that an “auto-number” or identity column meets this requirement.
You can list all identity columns in your database with the following query: