LINQ - 指定的转换在dataview使用中无效 [英] LINQ - Specified cast is not valid with dataview use

查看:919
本文介绍了LINQ - 指定的转换在dataview使用中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据传递的列获取行的存在。该列以数据库的形式显示为MultiSelect。

I am trying to get the presence of rows based on the passed col. The column is coming from the database as MultiSelect.

bool bCFPresent = IsMultiSelectCFPresent(dvDataTag, "MultiSelect");


public static bool IsPresent(DataView dvDataTag, string colName)
{
  return ((from DataRowView drv in dvDataTag
                     where drv.Row.Field<short>(colName) == 1
                     select drv).Count() > 0 ? true : false);  
}

但是我收到这个错误: -

But I am getting this error:-


System.InvalidCastException是用户代码未处理的


Message =指定的转换无效。
Source =System.Data.DataSetExtensions
StackTrace:
在System.Data.DataRowExtensions.UnboxT`1.ValueField(Object
值)
在系统。 Data.DataRowExtensions.Field [T](DataRow
row,String columnName)

System.InvalidCastException was unhandled by user code
Message="Specified cast is not valid." Source="System.Data.DataSetExtensions" StackTrace: at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value) at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)

请帮助。

推荐答案

问题似乎是名为 colName 的列的类型不能总而言之,你的代码似乎并没有太大的意义。每列的行数相同。相反,请尝试直接检查列,例如:

The problem seems to be that the type of the column named colName can't be casted to a short...
Overall, your code doesn't seem to make a whole lot of sense. The number of rows is the same for each column. Instead, try to check for the column directly, e.g like this:

public static bool IsPresent(DataView dvDataTag, string colName)
{
    return dvDataTag.Table.Columns.Cast<DataColumn>().
                                      Any(c => c.ColumnName == colName);
}

这篇关于LINQ - 指定的转换在dataview使用中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆