简体   繁体   English

如何将参数传递给 DataRow

[英]How to pass parameter to a DataRow

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.不知道海是代码问题还是LINQ的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;
    }

错误捕获

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"):调用(列号为 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();

This works:这有效:

DataTable filteredTable = table.AsEnumerable().Where(row =>
                           (row.Field<DateTime>(1) > startDate) && 
                           (row.Field<DateTime>(1) <= endDate)).CopyToDataTable();

It does not work for the last comment它不适用于最后一条评论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM