bahador arghavan
bahador arghavan

Reputation: 9

Error (Object cannot be cast from DBNull to other types

Please help and tell what am I doing wrong?

//For Only visible Rows After Filtering 
for(int i=0; i< DGScores.DataGridView.Rows.Count-1;i++)
{
    Int32 M1Val=Convert.ToInt32(DGScores.DataGridView.Rows[i].Cells["M1Val"].Value); 
    Int32 ScoreType=Convert.ToInt32(DGScores.DataGridView.Rows[i].Cells["ScoreType"].Value); 
    string StudentCode=DGScores.DataGridView.Rows[i].Cells["StudentCode"].Value.ToString();
    if(!Convert.IsDBNull(DGScores.DataGridView.Rows[i].Cells["M1Val"].Value))
    {
        if(  ScoreType==2 &&  M1Val >=0 )   
        { 
            MessageBox.Show("نمره مستمر اول برای "+StudentCode);  
        }
    }    
} 

Upvotes: 1

Views: 475

Answers (2)

user6611754
user6611754

Reputation:

One way to avoid this error with what your doing could be something like this.

Int32? M1Val = DGScores.DataGridView.Rows[i].Cells["M1Val"].Value == DBNull.Value ? 
(Int32?)null : Convert.ToInt32(DGScores.DataGridView.Rows[i].Cells["M1Val"].Value);

This will set it to null if it was actually a null or to the number if it wasn't. You can then use to check for null before entering your messagebox if statement

if(M1Val != null)
{
    if(  ScoreType==2 &&  M1Val >=0 )   
    { 
        MessageBox.Show("نمره مستمر اول برای "+StudentCode);  
    }
}

Hope this helps.

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176896

you can do like this and avoid error with dbnull

if(datarow["columnaname"] != DBNull.Value)
 object.property =  decimal.Parse(row["columnname"].ToString());

or create common method to use multiple places

 public static T GetColumnValue<T>(string columnName, DataRow dr)
 {
    Type typeParameterType = typeof(T);

    return dr[columnName] != DBNull.Value
                ? (T) Convert.ChangeType(dr[columnName] , typeParameterType)
                : default(T);
 }

use it like

 obj.property = GetColumnValue<int>("column", datarow);

Upvotes: 1

Related Questions