-1
public Int32 SQL_GetMaxValue(string TableName, string FieldName)
    {
        return SQL_GetMaxValue(TableName, FieldName, "");
    }

    public Int32 SQL_GetMaxValue(string TableName, string FieldName, string WhereCondition)
    {
        try
        {
            string SQLString = "SELECT MAX(" + FieldName + ") FROM " + TableName;
            if (WhereCondition != "") { SQLString += " WHERE " + WhereCondition; }

            objCN.Close();
            objCN.Open();
            SqlCommand objCMD = new SqlCommand(SQLString, objCN);
            Int32 MaxValue = Convert.ToInt32(objCMD.ExecuteScalar());
            objCN.Close();
            return MaxValue;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

Object cannot be cast from DBNull to other types.

this error i m getting

Edited by Ezzaral: Added code tags. Please use them to format any code that you post. Also, use a real title in the future - not "urgent".

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by mani-hellboy
0

This means your SQL statement is returning null from the database table. Check your SQL, especially if a where clause is being used, and make sure null isn't being returned.

-1

Hey Dude.,

I think there 2 way to handle this use try catch block on Execute scalar function if DBexception occurs in catch block manually assigning some value to MaxValue

Another way place isnull() function in query - I am not sure about secound method I am 100% sure 1st method will help you

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.