Israel

Israel

  • 701
  • 1.3k
  • 217.3k

Why the ID's number order its desobeyy sometime???

May 25 2019 4:34 AM
Hi! 
I have a very little problem but I need a great logic.
I have a DB with two columns (ID and name). Then to keep the ID's number in order even I delete one record anytime its delete only the ID's column and replace in order number. But what happen???
In the beginning its save records in order in my DB without problem:
ID  Name 
1    Alex
2    Shamin
3    Zim
4    Simon
5    Amin
 
Suddently in someway in saving process its can put the number 6 between the number 3 and 4. Mean that its doesnt obey saving in other as always. In need to know if something is wrong? Please see my code:
 
/////////////////////////Delete column ID in DB
if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand cmd = new SqlCommand();
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
try
{
cmd = new SqlCommand("ALTER TABLE livro1 DROP COLUMN ID", conn);
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
// /////////////////////////Recreate again the column ID in the DB
conn.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2 = new SqlCommand("ALTER TABLE livro1 ADD ID int IDENTITY(1,1)", conn);
cmd2.ExecuteNonQuery();
conn.Close();
///////////////////////// Refreshing the DB
if (conn.State != ConnectionState.Open)
conn.Open();
{
using (SqlDataAdapter ad = new SqlDataAdapter("SELECT [ID],[name] FROM Test order by ID", conn))
{
DataTable dt = new DataTable();
ad.Fill(dt);
myDgv.DataSource = dt;
myDgv.CurrentCell = myDgv.Rows[myDgv.Rows.Count - 1].Cells[0];
conn.Close();

Answers (1)