For some reason i don't want to use the auto-incrementing value of SQL Server and i want to make my own incrementing value for my Database IDs.
What Im trying to do is, for example i will add a Product. Im going to take the last value of the last ProductID by MAX query and add 1 then i will insert that value as the ProductID for the current product.
My code is something like this
private static int x;
private static int y = 1;
private static int z;
private static int ID;
private void AddnewProduct_Click(object sender, EventArgs e)
{
x = ID;
z = x + y;
lblProductIDnew.Text = Convert.ToString(z);
}
private void AddProduct_Load(object sender, EventArgs e)
{
crud.FillDataGrid("Select * From IDs", ref dgvIDs);
using (SqlConnection connection = new SqlConnection("Data Source=DESKTOP-MQKIBSK\\SQLEXPRESS;Initial Catalog=MARISCHELLdatabase;Integrated Security=True"))
{
connection.Open();
string query = "SELECT MAX(ProductID) FROM IDs";
SqlCommand cmd = new SqlCommand(query, connection);
ID = (int)cmd.ExecuteScalar();
lblProductID.Text = ID.ToString();
}
}
Is there an easier way to do this? Thanks everyone
UPDATE: The reason i don't want to use SQL auto-increment is when you Send a data to another database(archive) and when you want to restore it, you can't, because you cant enter a value to that identity column. thus the productID will change everytime you send a data to archive and restore it. And setting the identity on and off is not working. if there is a work-around here i will gladly use it. Thanks again everyone