Karan
Karan

Reputation: 3328

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 .

Upvotes: 0

Views: 2600

Answers (2)

abhilash
abhilash

Reputation: 5641

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

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174279

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

Upvotes: 1

Related Questions