Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public string generateSNo()
       {
           String str = "SELECT Max(std_ID) From tblStudent";
           string std_ID = null;
           SqlCommand con = new SqlCommand(str, cn);
           cn.Open();

           if (con.ExecuteScalar().Equals(DBNull.Value))
           {
               std_ID = "S001";
           }
           else
           {
               std_ID = (string)con.ExecuteScalar();

               //Display the new stdno (by get the last stdno from db)+1
               string[] splitCode = Strings.Split(std_ID, "S", 2);
               std_ID = "S00" + ((Convert.ToInt32(splitCode[1])) + 1).ToString();
           }

           cn.Close();
           return std_ID;
       }
Posted
Comments
vishal.shimpi 18-Dec-14 1:03am    
Have you checked, what will be the value in splitCode[1]? do check this it might be helpful for you.

1 solution

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:
C#
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); //To have values like: S001, S002, ..., S099, ..., S999!
           }
 
           cn.Close();
           return std_ID;
       }
 
Share this answer
 
v6
Comments
Member 11308948 18-Dec-14 0:51am    
is there any solution because i applied the same method for generate feedback no its work perfectly but to generate student no its showing error
Raul Iloc 18-Dec-14 0:55am    
See my update above!
Member 11308948 18-Dec-14 1:00am    
Input string was not in a correct format.
Raul Iloc 18-Dec-14 1:06am    
Did you debug your code?
What is the value of the ID that is read from the database? It is like "S001"?
Member 11308948 18-Dec-14 1:13am    
im getting the error

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900