0

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 .

abhilash
  • 5,605
  • 3
  • 36
  • 59
Karan
  • 3,265
  • 9
  • 54
  • 82

2 Answers2

1

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);
}
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0

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

abhilash
  • 5,605
  • 3
  • 36
  • 59
  • drv need not be defined. Isn't that the fun of using lamdas ? :) – abhilash May 04 '11 at 12:26
  • i tried to use the row count code given by you. But it is giving this error. Error 2 'System.Data.DataView' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'System.Data.DataView' could be found (are you missing a using directive or an assembly reference?) – Karan May 05 '11 at 10:52
  • @Karan have you included [System.Linq namespace ?](http://msdn.microsoft.com/en-us/library/system.linq.aspx) – abhilash May 09 '11 at 16:46