【问题标题】:Error (Object cannot be cast from DBNull to other types错误(对象不能从 DBNull 转换为其他类型
【发布时间】:2018-06-16 10:24:09
【问题描述】:

请帮忙告诉我我做错了什么?

//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);  
        }
    }    
} 

【问题讨论】:

    标签: c# dbnull


    【解决方案1】:

    您可以这样做并避免 dbnull 出错

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

    或创建通用方法以使用多个位置

     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);
     }
    

    像这样使用它

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

    【讨论】:

      【解决方案2】:

      避免这种错误的一种方法可能是这样。

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

      如果它实际上是一个空值,这会将它设置为空值,如果它不是,它会设置为数字。然后,您可以在输入消息框 if 语句之前使用它来检查 null

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

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2011-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多