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

Recommended Answers

All 2 Replies

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.