当前位置: 移动技术网 > IT编程>开发语言>c# > 如何判断当前修改过的datatable的某一列值是否为int型或double类型

如何判断当前修改过的datatable的某一列值是否为int型或double类型

2019年08月09日  | 移动技术网IT编程  | 我要评论

如何判断当前修改过的datatable的某一列值是否为int型或double类型

今天在做datatable数据验证时碰到要对datatable的列数据进行数据类型校验,因此记录一下本人校验的方法,如果还有更简单的校验方式,欢迎大家踊跃分享,不胜感激。

/*
取得改变过的datatable,注意不能把原有的datatable执行acceptchanges()方法,先执行copy()新得到一个
当前经过修改后datatable
*/
datatable dttemp = ((datatable)gridcontrol1.datasource).copy();
 dttemp.acceptchanges();
//判断datatable是否为空
if (dttemp.rows.count == 0)
{
   if(commonfunction.showmsgbox("检测到复称列表为空,是否直接保存", messageboxbuttons.yesno, 0) == dialogresult.no)
   {
      return false;
   }
}
//以下是判断当前经过修改后datatable是否有空值并若为空值则校验不通过,若不为空值再进行数据类型的校验
if (dttemp.rows.count > 0)
{
   foreach (datarow dr in ((datatable)gridcontrol1.datasource).rows)
   {
      if (commonfunction.trim(convert.tostring(dr["序号"]))=="")
      {
         commonfunction.showmsgbox("检测到复称列表有未填项");
        return false;
       }
       /*
       通过int.tryparse(string s out int32 result)进行整数类型的校验
       该方法传入两个参数,第一个是字符串类型,第二个是转化成功后输出的整型变量
       如果转化成功则该方法返回true并输出转化后的结果,该结果可进一步被使用来判断数值范围 
       如果转化失败则该方法返回false,即该datatable的该单元格中的内容不数据类型错误    
       */
      int irecordseq;          
      if(int.tryparse(convert.tostring(dr["序号"]),out irecordseq) == false || irecordseq < 1)
      {
         commonfunction.showmsgbox("复称列表序号必须为大于0的整数");
         return false;
       }
       if (commonfunction.trim(convert.tostring(dr["桶皮"])) == "")
        {
          commonfunction.showmsgbox("检测到复称列表有未填项");
          return false;
        }
        double dtaerweight;
        if (double.tryparse(convert.tostring(dr["桶皮"]), out dtaerweight) == false || dtaerweight < 1)
         {
            commonfunction.showmsgbox("复称列表桶皮必须为大于0的数字");
           return false;
         }
         if (commonfunction.trim(convert.tostring(dr["毛重"])) == "")
         {
            commonfunction.showmsgbox("检测到复称列表有未填项");
            return false;
         }
         double dgrossweight;
         if (double.tryparse(convert.tostring(dr["毛重"]), out dgrossweight) == false || dgrossweight < 1)
         {
            commonfunction.showmsgbox("复称列表毛重必须为大于0的数字");
          return false;
         }
         if (commonfunction.trim(convert.tostring(dr["单位"])) == "")
         {
            commonfunction.showmsgbox("检测到复称列表有未填项");
            return false;
         }                 
     }
}    
//遍历当前修改过后的datatable,看序号这一列是否存在重复的值
foreach (datarow dr in dttemp.rows)
{
  int irecordseq=convert.toint32(dr["序号"]);
  if (dttemp.select("序号=" + irecordseq).count() > 1)
  {
     commonfunction.showmsgbox("检测到复称列表有重复的序号,请检查无误后操作");
     return false;
   }            
}
return true;

至此,校验完成。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网