hi micah,
Kindly refer below sample.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download the database table SQL by clicking the download link below.
Download SQL file
HTML
<asp:TextBox ID="txtrecipt" runat="server" CssClass="form-control" placeholder="Recipt" ReadOnly="True"></asp:TextBox>
<asp:Label ID="lblrecipt" runat="server"></asp:Label>
<asp:LinkButton ID="btnrecipt" runat="server" CssClass="btn btn-default" OnClick="SetId">Call Receipt</asp:LinkButton>
Namespaces
C#
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data.SqlClient
Imports System.Configuration
Code
C#
protected void SetId(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string previousIdQuery = "SELECT MAX(CustomerId) FROM Customers";
txtrecipt.Text = GenerateNewId(connStr, previousIdQuery);
string insertQuery = "INSERT INTO Customers (CustomerId) VALUES(" + GenerateNewId(connStr, previousIdQuery) + ")";
using (SqlConnection con = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand(insertQuery, con);
con.Open();
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();
if (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
Protected Sub SetId(ByVal sender As Object, ByVal e As EventArgs)
Dim connStr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim previousIdQuery As String = "SELECT MAX(CustomerId) FROM Customers"
txtrecipt.Text = GenerateNewId(connStr, previousIdQuery)
Dim insertQuery As String = "INSERT INTO Customers (CustomerId) VALUES(" & GenerateNewId(connStr, previousIdQuery) & ")"
Using con As SqlConnection = New SqlConnection(connStr)
Dim cmd As SqlCommand = New SqlCommand(insertQuery, con)
con.Open()
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()
If dr.Read() Then
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 If
con.Close()
End Using
Return String.Concat(newId)
End Function
Screenshot