Total string length is 5 chars. I have a scenario, ID starts with: A0001 and ends with: A9999, B0001 to B9999
Now,
How to create this format?
I tried:
int a;
using (SqlCommand command2 = new SqlCommand("select * from voiceno WHERE ID = '1'", con))
{
con.Close();
con.Open();
SqlDataReader dr;
dr = command2.ExecuteReader();
if (dr.Read())
{
string val = dr["voiceno"].ToString();
if (val == "0")
{
txtinvoiceno.Text = "00001";
}
else
{
a = Convert.ToInt32(dr["voiceno"].ToString());
a = a + 1;
txtinvoiceno.Text = a.ToString("00000");
}
}
}
My table looks like
CREATE TABLE [dbo].[voiceno](
[ID] [int] IDENTITY(1,1) NOT NULL,
[voiceno] [nvarchar](50) NULL)
You can have a function that gets current value and gives you the next value:
public string Next(string cur)
{
int num = int.Parse(cur.Substring(1));
char chr = cur[0];
num++;
if (num > 9999)
{
num = 0;
chr++;
}
return chr + num.ToString().PadLeft(4, '0');
}
To make it get last one from database:
You can get the current biggest ID from database like:
select Max(id) from voiceno
Also look at Custom Auto-Generated Sequences with SQL Server