Click here to Skip to main content
15,895,774 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
HI!!
I create table named "LateFee" and RctNo as Primary key and also i write one function "Autoge" and call it on button's (Add) clilk event but it throw exception "cast specified is not valid" what should i do for generating number as auto generate ..
C#
public void Autogen()
       {
           #region Autogen

           cmd = new SqlCommand("select max(RctNo) from LateFee ",con);
           cmd.Connection = con;
           int i=0;
           try
           {
               if (con.State == ConnectionState.Closed)
               {
                   con.Open();
               }
              i =(int)cmd.ExecuteScalar();
               i = i++;
               txtrctno.Text =i.ToString();
               con.Close();
           }
           catch(InvalidCastException ex)
           {
               MessageBox.Show(ex.Message);
               con.Close();
           }
           #endregion

       }

thanks
Posted
Updated 25-Mar-13 1:16am
v2

That is a very, very bad idea.
Even if it worked, getting the highest number from the database and incrementing it by one does not ensure that teh number is unique - indeed, it may not be unique by the time you exit the method. Remember that SQL server is designed to work in a multiuser environment, so you have to assume that another user or users will be doing the exact same code at the exact same time. You should never, ever try to predict the "next value" of an identity field in advance - get the value for the row after you have inserted a new row and you are fine, but getting it in advance is just asking for complicated trouble in production.

"Then Sir what will be the command to be execute for getting next row????"

You don't. You only get the id of a row after you have created it. The easy way is to do the insert and select as a single operation:
SQL
INSERT INTO MyTable (UserName, UserRole) VALUES ('My Name', 666);
SELECT @@IDENTITY
Because this is executed as a single statement by SQL, it will return the value given to the Identity field by the insert.
 
Share this answer
 
v2
Comments
Arifa S 25-Mar-13 7:29am    
Then Sir what will be the command to be execute for getting next row????
OriginalGriff 25-Mar-13 7:50am    
Answer updated
in your table what is data type of "RctNo" column. You can try this
Corrct this Line.
cmd = new SqlCommand("select max(Cast(RctNo as Integer)) from LateFee ",con);
 
Share this answer
 
Comments
Arifa S 25-Mar-13 7:31am    
RctNo datatype is Int
OriginalGriff 25-Mar-13 7:50am    
That is a very dangerous thing to do: see my answer!
Arifa S 25-Mar-13 8:02am    
Means its better to use simple code instead of using auto generated code...
right sir
thanks

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