How to autoincrement value of any particular column in

Looking for code in to do auto incrementing in some column from database? I will be providing here code for auto incremnting values in a column.

Sometimes we need to autoincrement values while inserting the new data so that each time we will get new unique number. In that scenarios this code will be useful. This code has been developed in I hope you will utilize it in your web applications.

How to autoincrement value of any particular column in

To autoincrement value of some column , say id , we have to use following piece of code

public int AutoIncrement_Value_In_database()
int myCounter = 0;
string connectionString = "Data Source=your_server_name;
Initial Catalog=your_databasename;Integrated Security=True;";
SqlConnection sqlConnection = new SqlConnection(connectionString);
DataSet objSet = new DataSet();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "Select count(columnname) As Totcount FROM tablename";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;

if (objSet.Tables.Count > 0)
foreach (DataRow dr in objSet.Tables[0].Rows)
myCounter = Convert.ToInt32(dr["Totcount"].ToString());
return myCounter;

Put this code in yourpage.aspx.cs

protected void Page_Load(object sender, EventArgs e)
int tot = AutoIncrement_Value_In_database();
tot = tot + 1;
your_textboxname.Text = Convert.ToString(tot); /*this will display autoincremented value.
You can put readonly property as true for this textbox.*/



No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: