In this article, we will fetch the last entered ID say CustomerID from the CustomerDetails table of the MS Access Database and increment it by 1. We can use this ID anywhere in our application say to use it in the new record etc.
NOTE: If you are using SQL Database, you can replace OleDbConnection and OleDbCommand with SQLConnection and SQLCommand respectively.
If there is no record in the table, this code also checks for that null condition and start the ID from a particular value say 100. We are returning the ID for it to be used at other places in our application.
public static string getCutomerID()
{
string strCmd = "SELECT MAX(CustomerID) FROM CustomerDetails";
string custID;
using(OleDbConnection conn=new OleDbConnection(connectionString))
{
try
{
OleDbCommand cmd = new OleDbCommand(strCmd, conn);
conn.Open();
object obj = cmd.ExecuteScalar();
if (obj == DBNull.Value)
custID = "100";
else
custID = (Convert.ToInt32(obj) + 1).ToString();
return custID;
}
catch (Exception ex)
{
return null;
}
}
}
You can use this function to display CustomerID in a TextBox, txtCustomerID:
txtCustomerID.Text= getCutomerID();
