how to get the next autoincrement value in sql

Viewed 68049

I am creating a winform application in c#.and using sql database.

I have one table, employee_master, which has columns like Id, name, address and phone no. Id is auto increment and all other datatypes are varchar.

I am using this code to get the next auto increment value:

string s = "select max(id) as Id from Employee_Master";
SqlCommand cmd = new SqlCommand(s, obj.con);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int i = Convert.ToInt16(dr["Id"].ToString());
txtId.Text = (i + 1).ToString();

I am displaying on a textBox.

But when last row from table is deleted, still I get that value which is recently deleted in textbox

How should I get the next autoincrement value?

10 Answers

As for me, the best answer is:

dbcc checkident(table_name)

You will see two values (probably same) current identity value , current column value

 SqlConnection con = new SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=databasename;User ID=sa;Password=123");
 con.Open();
 SqlCommand cmd = new SqlCommand("SELECT TOP(1) UID FROM InvoiceDetails ORDER BY 1 DESC", con);

 SqlDataReader reader = cmd.ExecuteReader();

 //won't need a while since it will only retrieve one row
 while (reader.Read())
 {
     string data = reader["UID"].ToString();
     //txtuniqueno.Text = data;
     //here is your data
     //cal();
     //txtuniqueno.Text = data.ToString();
     int i = Int32.Parse(data);
     i++;
     txtuid.Text = i.ToString();
  }
Related