1. The error is generated by the fact that you are expecting that the
Split
to gave you 2 results, but in your case its return only one string like "
001
".
2.Other problem is that you are running the same
SqlCommand
twice, so you should modify your code like below:
public string generateSNo()
{
String str = "SELECT Max(std_ID) From tblStudent";
string std_ID = null;
SqlCommand con = new SqlCommand(str, cn);
cn.Open();
object result = con.ExecuteScalar();
if (result == DBNull.Value)
{
std_ID = "S001";
}
else
{
std_ID= (string)result;
string[] splitCode = std_ID.Split(new char[]{'S'}, 2, StringSplitOptions.RemoveEmptyEntries);
int id = 0;
int.TryParse(splitCode[0], out id);
id++;
std_ID = string.Format("S{0:D3}", id);
}
cn.Close();
return std_ID;
}