0
votes

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 .

2
What type is 'colName' in the DB?Nasmi Sabeer

2 Answers

1
votes

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

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