Click here to Skip to main content
15,914,413 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
private void ClassFrom_Load(object sender, EventArgs e)
        {
             TxtClassID.Text = FunGetMaxID() ;
        }


        private string FunGetMaxID ()
        {

         try
            {
                con = new SqlConnection(cs.Dbcon);
                con.Close();
                string sql =  "Select isnull(max(ClassId),0)+1  as Id from Class ";
                SqlCommand cmd = new SqlCommand(sql, con);
                cmd.CommandType = CommandType.Text;
                             
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();

                FunGetMaxID() = (reader["id"]);

                reader.Close();
                cmd.Dispose();
                con.Close();

               // return FunGetMaxID;

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error", "Message" + ex.Message);
            }
Posted
Updated 8-Oct-15 3:58am
v2
Comments
IrfanfromMultanPakistan 8-Oct-15 10:22am    
magar phir bi method ust nai ho raha err ha
IrfanfromMultanPakistan 8-Oct-15 10:23am    
cant use method

Below I give you some advice on your code. However I have grave concerns about this function. It looks as if you are attempting to find the maximum current id in order to assign the next value. This is a very bad design! What if another user adds another record while this code is running? (Very likely in multi-user environments). Far better is to use the right tool for the job - an Identity column[^] on the database


Code Review:

First look at the line
C#
FunGetMaxID() = (reader["id"]);
That is very VB6 in style and will result in the compile error
Quote:
The left-hand side of an assignment must be a variable, property or indexer

Next - learn about the using statement[^] - it is especially useful for working with sql connections. You do not need to explicitly close the connection nor Dispose of it.
While we're on that subject, look at
C#
con = new SqlConnection(cs.Dbcon);
con.Close();
There is no point in that .Close() - you have only just created the object!

Now consider your sql statement
SELECT ISNULL(MAX(ClassId),0)+1  AS Id FROM Class
It is better to handle the potential to be null at the source rather than escalating a null up calculations/functions/etc i.e. this would be better
SELECT MAX(ISNULL(ClassId,0)) AS Id FROM Class

The next problem is that you have
C#
private string FunGetMaxID ()
but the maximum Id is likely to be an integer, so you should be returning an integer from your function. Note as well, the way you have named the function implies that you want the existing maximum value for id - but you are returning the maximum plus 1. Either rename your function or return the correct value

As Manas_Kumar has suggested, it is more appropriate to use ExecuteScalar[^] in this instance (you don't have to, it's just more appropriate)

Regarding the Try-Catch block, you may also find these articles useful: Exception Handling Best Practices in .NET[^] and Best Practices for Exceptions - MSDN[^]

I would do something like
C#
private int FunGetMaxID()
{
    var maxId = 0;

    try
    {
        using (var con = new SqlConnection(cs.Dbcon))
        {
            con.Open();
            const string sql = "Select max(IsNull(ClassId,0)) as Id from Class ";

            using (var cmd = new SqlCommand(sql, con))
            {
                cmd.CommandType = CommandType.Text;
                maxId = (int)cmd.ExecuteScalar();
            }
        }
    }
    catch (SqlException ex)
    {
        MessageBox.Show("Error", "Message" + ex.Message);
    }
    return maxId;
}
 
Share this answer
 
Comments
IrfanfromMultanPakistan 8-Oct-15 12:35pm    
but problam is how to get max ID and use in same calss or from in many time therefore how to posible?

TxtClassID.Text = FunGetMaxID();
CHill60 8-Oct-15 12:40pm    
The method FunGetMaxID can be made private to the class ClassFrom_Load ... I'll update my solution
Just realised that ClassFrom_Load is a private method within a form. As is FunGetMaxID so TxtClassId.Text = FunGetMaxID().ToString(); should work (if you are using the code from my solution)
IrfanfromMultanPakistan 8-Oct-15 13:16pm    
Specified cast is not valid runging time errr how to solve
CHill60 8-Oct-15 13:57pm    
On which line?
If it is on maxId = (int)cmd.ExecuteScalar(); then change it to int64 maxId = 0 and maxId = (int64)cmd.ExecuteScalare();
IrfanfromMultanPakistan 8-Oct-15 14:15pm    
thanks Really thanks to you chill60
http://www.codeproject.com/script/Membership/View.aspx?mid=4884011
Try with below code:
C#
con = new SqlConnection(cs.Dbcon);
con.Close();
string sql =  "SELECT ISNULL(MAX(ClassId),0)+1  AS Id FROM Class";

SqlCommand cmd = new SqlCommand(sql, con);
cmd.CommandType = CommandType.Text;

con.Open();
int newProdID = (Int32)cmd.ExecuteScalar();

reader.Close();
cmd.Dispose();
con.Close();

As you need single column value, you need to use ExecuteScalar() to get the value.
 
Share this answer
 
v2

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