sarode111 sarode111 - 1 month ago 6
ASP.NET (C#) Question

AutoGenrate the code

protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["Dum01"].ConnectionString;
using (var scon = new SqlConnection(cs))
{
string codevalue = TextBox1.Text.Substring(0, 1);
var query = "SELECT MAX(CODE) AS TCODE FROM AgentMast WHERE LEFT(CODE,1)= @SearchText";
using (var cmd = new SqlCommand(query, scon))
{
cmd.Parameters.AddWithValue("@SearchText",codevalue);
cmd.CommandType = CommandType.Text;
cmd.Connection = scon;
scon.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{

while (sdr.Read())
{
TextBox2.Text= sdr["TCODE"].ToString();
}
string codewithnumber = TextBox2.Text.Substring(1, 4);
Label2.Text = codewithnumber;
Label1.Text = (int.Parse(Label2.Text) + 1).ToString();
string firstchar=TextBox2.Text.Substring(0,1);
Label3.Text = firstchar + Label1.Text+"A" ;
}
scon.Close();
}
}

}


when in the textbox some text is entered then according to the first letter it selects the max code from AgentMast table. When I get the max code then I need to increment by one. For example if code found Z0001A then on next insert it should be Z0002A. 'A' is fixed for the agent table and also when TCODE is not found then I need to create new code with first character of textbox text and then 0001 and then fix character 'A'. How to solve? Thanks in Advance.

Answer

Try this:

oldCode = sdr["TCODE"].ToString();

if (string.IsNullOrEmpty(oldCode))
{
    newCode = codevalue + "0001A";
}
else
{
    int newIncrement = Convert.ToInt32(oldCode.Substring(1, 4)) + 1;
    newCode = codevalue + newIncrement.ToString().PadLeft(4, '0') + oldCode.Substring(5, 1);
}