”datatable在位置0处没有任何行“解决方案

  使用datatable在查询数据中,如果查询的数据不存在,就会报出“在位置0处没有任何行” 的错误。因此首先应该判断一下该表是否为空;

  由于在查询中使用了SQLHelper并且返回一个datatable,这就导致了可能出现空内容的情况。在B层中应该加上如下一句:

 

If (table.Rows.Count > 0) Then
这样就提前判断出表的行数是否为空,大于0则执行程序,否则就可以

 1.try...catch的出错处理;

 2.这层我返回的是一个实体类studentEntity,可以返回一个空的studentEntity。如下:

 If (table.Rows.Count > 0) Then

            student.CardID = table.Rows(0)("cardID").ToString()
            student.UserID = table.Rows(0)("userID").ToString
            student.UserName = table.Rows(0)("userName").ToString
            student.UserSex = table.Rows(0)("userSex").ToString
            student.UserDepart = table.Rows(0)("userDepart").ToString
            student.UserGrade = table.Rows(0)("userGrade").ToString
            student.UserClass = table.Rows(0)("userClass").ToString
            student.UserFee = table.Rows(0)("userFee").ToString
            student.UserState = table.Rows(0)("userState").ToString
            student.UserPlain = table.Rows(0)("userPlain").ToString
            Return student
        Else
            Return New StudentEntity

        End If
  这样就解决了datatable在位置0处没有任何行的错误。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
Datatable类型不能使用AsEnumerable()方法的原因已经在上面回答过了。下面是一些解决方案及代码: 1. 使用DataTableExtensions类中的方法进Linq查询,例如CopyToDataTable()、AsDataView()等。 代码示例: ```csharp using System.Data; using System.Linq; ... // 创建一个DataTable对象 DataTable dt = new DataTable(); // 添加列 dt.Columns.Add("Id", typeof(int)); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Age", typeof(int)); // 添加数据 dt.Rows.Add(1, "Tom", 18); dt.Rows.Add(2, "Jerry", 20); dt.Rows.Add(3, "Lucy", 22); // 使用DataTableExtensions类中的CopyToDataTable()方法进Linq查询 var result = dt.AsEnumerable().Where(r => r.Field<int>("Age") > 20).CopyToDataTable(); // 输出结果 foreach (DataRow row in result.Rows) { Console.WriteLine(row["Id"] + "\t" + row["Name"] + "\t" + row["Age"]); } ``` 2. 将DataTable类型转换为IEnumerable类型,再使用AsEnumerable()方法进Linq查询。 代码示例: ```csharp using System.Data; using System.Linq; ... // 创建一个DataTable对象 DataTable dt = new DataTable(); // 添加列 dt.Columns.Add("Id", typeof(int)); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Age", typeof(int)); // 添加数据 dt.Rows.Add(1, "Tom", 18); dt.Rows.Add(2, "Jerry", 20); dt.Rows.Add(3, "Lucy", 22); // 将DataTable类型转换为IEnumerable类型 IEnumerable<DataRow> rows = dt.Rows.Cast<DataRow>(); // 使用AsEnumerable()方法进Linq查询 var result = rows.AsEnumerable().Where(r => r.Field<int>("Age") > 20); // 输出结果 foreach (DataRow row in result) { Console.WriteLine(row["Id"] + "\t" + row["Name"] + "\t" + row["Age"]); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值