For this you need to store last generated Id somewhere.(i.e. in Database) like below.
SQL
CREATE TABLE GenerateUniqueId
(
ID INT IDENTITY,
UniqueId INT NOT NULL
)
HTML
<asp:Button Text="CId" runat="server" OnClick="NewCId" />
<br />
New CID: <asp:Label ID="lblNewCId" runat="server" ForeColor="Red" />
Code
C#
string connStr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
protected void NewCId(object sender, EventArgs e)
{
string previousCidQuery = "SELECT MAX(UniqueId) UniqueId FROM GenerateUniqueId";
int newCID = GenerateNewCID(connStr, previousCidQuery);
lblNewCId.Text = newCID.ToString();
string insertQuery = "INSERT INTO GenerateUniqueId VALUES(" + newCID + ")";
InsertNewCID(connStr, insertQuery);
}
private void InsertNewCID(string connection, string query)
{
using (SqlConnection con = new SqlConnection(connection))
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
private int GenerateNewCID(string connection, string query)
{
string newCID = 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))
{
newCID = DateTime.Now.ToString("yyMM") + "0000";
}
else
{
i = i.Substring(4);
int j = Convert.ToInt32(i);
j = j + 1;
newCID = DateTime.Now.ToString("yyMM") + j.ToString().PadLeft(4, '0');
}
}
con.Close();
}
return int.Parse(newCID);
}
VB.Net
Private connStr As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Protected Sub NewCId(ByVal sender As Object, ByVal e As EventArgs)
Dim previousCidQuery As String = "SELECT MAX(UniqueId) UniqueId FROM GenerateUniqueId"
Dim newCID As Integer = GenerateNewCID(connStr, previousCidQuery)
lblNewCId.Text = newCID.ToString()
Dim insertQuery As String = "INSERT INTO GenerateUniqueId VALUES(" & newCID & ")"
InsertNewCID(connStr, insertQuery)
End Sub
Private Sub InsertNewCID(ByVal connection As String, ByVal query As String)
Using con As SqlConnection = New SqlConnection(connection)
con.Open()
Dim cmd As SqlCommand = New SqlCommand(query, con)
cmd.ExecuteNonQuery()
con.Close()
End Using
End Sub
Private Function GenerateNewCID(ByVal connection As String, ByVal query As String) As Integer
Dim newCID 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
newCID = DateTime.Now.ToString("yyMM") & "0000"
Else
i = i.Substring(4)
Dim j As Integer = Convert.ToInt32(i)
j = j + 1
newCID = DateTime.Now.ToString("yyMM") & j.ToString().PadLeft(4, "0"c)
End If
End While
con.Close()
End Using
Return Integer.Parse(newCID)
End Function
Screenshot