开发者

LINQ - Specified cast is not valid with dataview use

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

Please help .


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


I'm not really sure what you're trying to do in your predicate

drv.Row.Field<short>(colName) == 1

But your IsPresent Method can be rewritten as

Update:

public static bool IsPresent(DataView dvDataTag, string colName)
{

        return dvDataTag.Any(drv => string.Equals("1",drv[colName].ToString()));
}

For the Row Count

int count =  dvDataTag.Count(drv => string.Equals("1",drv[colName].ToString()));

PS: Handling of nulls is left to the OP

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜