How to autoincrement value of any particular column in ASP.net?
Looking for code in asp.net 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 ASP.net. I hope you will utilize it in your web applications.How to autoincrement value of any particular column in ASP.net?
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;
sqlDataAdapter.Fill(objSet);
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.*/
}