For this you need to insert the number in database. On refresh retrieve the data from database and increment the value.
Check the below sample code.
SQL
CREATE TABLE GenerateUniqueId
(
ID INT IDENTITY,
UniqueId INT NOT NULL
)
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Code
C#
string connStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
private void Page_Load(object sender, EventArgs e)
{
string previousIdQuery = "SELECT MAX(UniqueId) UniqueId FROM GenerateUniqueId";
string newId = GenerateNewId(connStr, previousIdQuery);
lblId.Text = newId;
string insertQuery = "INSERT INTO GenerateUniqueId VALUES(" + newId + ")";
using (SqlConnection con = new SqlConnection(connStr))
{
con.Open();
SqlCommand cmd = new SqlCommand(insertQuery, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
private string GenerateNewId(string connection, string query)
{
string newId = string.Empty;
using (SqlConnection con = new SqlConnection(connection))
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string i = dr[0].ToString();
if (string.IsNullOrEmpty(i))
{
newId = "1";
}
else
{
int j = Convert.ToInt32(i);
j = j + 1;
newId = j.ToString();
}
}
con.Close();
}
return string.Concat(newId);
}
VB.Net
Private connStr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim previousIdQuery As String = "SELECT MAX(UniqueId) UniqueId FROM GenerateUniqueId"
Dim newId As String = GenerateNewId(connStr, previousIdQuery)
lblId.Text = newId
Dim insertQuery As String = "INSERT INTO GenerateUniqueId VALUES(" & newId & ")"
Using con As SqlConnection = New SqlConnection(connStr)
con.Open()
Dim cmd As SqlCommand = New SqlCommand(insertQuery, con)
cmd.ExecuteNonQuery()
con.Close()
End Using
End Sub
Private Function GenerateNewId(ByVal connection As String, ByVal query As String) As String
Dim newId As String = String.Empty
Using con As SqlConnection = New SqlConnection(connection)
con.Open()
Dim cmd As SqlCommand = New SqlCommand(query, con)
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim i As String = dr(0).ToString()
If String.IsNullOrEmpty(i) Then
newId = "1"
Else
Dim j As Integer = Convert.ToInt32(i)
j = j + 1
newId = j.ToString()
End If
End While
con.Close()
End Using
Return String.Concat(newId)
End Function