How to pass parameter to a DataRow

-3

I have a very peculiar problem, I am filtering a table according to a range of dates, and everything works fine when the column number is specified directly, but in the absence of this method. , since, I get that "The specified conversion is not valid". I do not know if the sea is a code problem or is a LINQ's bug. I leave the two cases.

works ok:

public DataTable GetTableByDate(DataTable table, DateTime startDate, DateTime endDate, int columnNumber)
    {
        var filteredRows = from row in table.Rows.OfType<DataRow>()
                           where (DateTime)row[1] > startDate 
                           where (DateTime)row[1] <= endDate select row;
        var filteredTable = table.Clone();
        filteredRows.ToList().ForEach(r => filteredTable.ImportRow(r));
        return filteredTable;
    }

doesn't works:

public DataTable GetTableByDate(DataTable table, DateTime startDate, DateTime endDate, int columnNumber)
    {
        var filteredRows = from row in table.Rows.OfType<DataRow>()
                           where (DateTime)row[columnNumber] > startDate // Error
                           where (DateTime)row[columnNumber] <= endDate select row; // Error
        var filteredTable = table.Clone();
        filteredRows.ToList().ForEach(r => filteredTable.ImportRow(r));
        return filteredTable;
    }

error capture

System.InvalidCastException
HResult=0x80004002
Message=La conversión especificada no es válida.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>

invoke (columnNumber is static "1"):

    try
    {
        startDate = DateTime.Parse(Session["FCDstartDate"].ToString());
    }
    catch (Exception)
    {
        startDate = DateTime.Now;
    }

    grdTest.DataSource = mergeTables.GetTableByDate(dataTable, startDate, 
     startDate.AddDays(14), 1);
    grdTest.DataBind();
c#
linq
asked on Stack Overflow Feb 1, 2018 by Jorge Luis Alcantara • edited Feb 1, 2018 by Jorge Luis Alcantara

1 Answer

1

This works :

DataTable filteredTable = table.AsEnumerable().Where(row =>
                           (row.Field<DateTime>(1) > startDate) && 
                           (row.Field<DateTime>(1) <= endDate)).CopyToDataTable();
answered on Stack Overflow Feb 1, 2018 by jdweng

User contributions licensed under CC BY-SA 3.0