Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello every one ...I've just started C# programming
problem scenario-
I've taken a table MaintenanceInfo in SQL DB. & assigned primary key to 'ID' column. while adding data through C# I want to add the 'current Id value + 1' & display it into Maintenance ID TextBox. that means if there are 4 records stored then while inserting next record the Maintenance ID should be 5 .

p.s. while adding info I've disabled this Textbox to avoid manual entry as a ID


What I have tried:

public void autoID()
{
con.Open();
string query = "SELECT MAX(MaintenanceID) FROM MaintenanceInfo";
SqlCommand cmd = new SqlCommand(query, con);
int ID = (int)cmd.ExecuteScalar();
ID = ID + 1;
tbMaintID.Text = ID.ToString();
con.Close();
//with this code it shows error -connection still open.....

}
private void MaintenanceDetails_Load(object sender, EventArgs e)
{
autoID();
}
Posted
Updated 18-Feb-16 0:49am

1 solution

Don't.
That's a very dangerous way to do things.
Instead, use an IDENTITY field in your database and let SQL sort out the value for you. The problem with getting the maximum and incrementing it yourself is that it works fine in development, but as soon as you get to production it gives intermittent problems because two or more users end up trying to use the same ID value.

See here: Identity column - Wikipedia, the free encyclopedia[^] and here: SQL AUTO INCREMENT a Field[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900