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

                if (con.ExecuteScalar().Equals(DBNull.Value))
                {
                    fNo = "F01";
                }
                else
                {
                     fNo = con.ExecuteScalar();

         //Display the new fdkno (by get the last fdkno  from db)+1
                    string[] splitCode = Strings.Split(fNo, "F", 2);
                  fNo = "F0" + ((Convert.ToInt32(splitCode[1])) + 1).ToString();
                }

                cn.Close();
            }
        }
Posted
Updated 16-Dec-14 2:23am
v2

Change from
Quote:
fNo = con.ExecuteScalar();
to
fNo = (string) con.ExecuteScalar();
 
Share this answer
 
you are assign object to a string. as the answer1 explains you can fix the issue but!
if you trying to get the next fdk_No based on this result you will end up with several issues.
if two users connect and try to get the max id, both of them will have the same next fdk_No. when they insert records you will have duplicates or if you have unique or primary key then on of the insert will fail.
you better separate the string part of the fdkno and the numeric part in separate columns. numeric part can be set auto incremented, then you don't need to worry about duplicates and also you don't need to read current maximum value before insert. database will handle all of these.
when you need to get the fdk_No you can join these two column values in the select statement and get it as one value. hope this helps.
 
Share this answer
 

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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