Search code examples
c#sql-serverauto-increment

Auto generate and AutoIncrement ID in C# when trying to add new record to database


I'm using this code to select the maxID from a database table and each time I want to add a new record, the autogenerated ID is not the last one +1.

 public formularAddCompanie()
    {

        InitializeComponent();
        try
        {
            string cs = "Data Source=CODRINMA\\CODRINMA;Initial Catalog=TrafficManager;Integrated Security=True";
            string select = "SELECT max(IDCompanie) FROM Companii";

            using (SqlConnection con = new SqlConnection(cs))
            {
                con.Open();
                SqlCommand cmd2 = new SqlCommand(select, con);
                SqlDataReader sda = cmd2.ExecuteReader();
                DataTable idmax = new DataTable("idmax");
                idmax.Load(sda);
                if (idmax.Rows[0][0].ToString().Trim() == "") { txtID.Text = "1"; }
                else { txtID.Text = (int.Parse(idmax.Rows[0][0] .ToString() + 1).ToString()); }
            }
        }
        catch (Exception er) { MessageBox.Show(er.Message); }
    }

The table from where the selection is made, looks like this:

IDCompany   Name   Address   City  RegNo
1           A      Street    NY    123

Each time I want to add a new record, the autogenerated ID is like this: 11, 111, 1111. It takes the last ID and add another 1 next to it. What am I missing?


Solution

  • Interestingly, note that

    string a = "The meaning of life is " + 42;
    

    converts 42 to a string, creating the result

    a == "The meaning of life is 42"
    

    Look at this code:

    (int.Parse(idmax.Rows[0][0] .ToString() + 1).ToString()); }
    

    You are converting idmax.Rows[0][0] to a string and adding +1 to the end of the string rather than to an integer value. Try

    (int.Parse(idmax.Rows[0][0].ToString()) + 1).ToString(); }
    

    Note that idmax.Rows[0][0] should already have an integer in it (as pointed out in the comments). If that's the case, you can simplify to

    (idmax.Rows[0][0] + 1).ToString(); }