How to get maximum ID from a Table in code behind using C# .Net

Last Reply on Oct 09, 2014 07:58 AM By Azim

Posted on Oct 09, 2014 07:48 AM

How can we generate pid increment one greater than last record how can we do this if front end asp.net(c#) back end database.

You are viewing reply posted by: Azim on Oct 09, 2014 07:58 AM.
Posted on Oct 09, 2014 07:58 AM

One way is to make the PId Column auto increment. Other way it to get the max Pid value from Database increment it by 1 then insert it into the Database.

You can refer this question as a reference.

Insert Data from GridView bound using ViewState to Database Table in ASP.Net

Please focus on these two functions.

private int GetMaxId()
{
    int pid = 0;
    string constr = ConfigurationManager.ConnectionStrings["ConString2"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT MAX(Id) AS ID FROM Person", con))
        {
            con.Open();
            pid = Convert.ToInt32(cmd.ExecuteScalar()) + 1;
            con.Close();
            return pid;
        }
    }
}

private void Save()
{
    //Write the Saving code here
    int pid = GetMaxId();
    // Save this Pid value in Database
}