简体   繁体   English

Linq结果Int错误:指定的强制转换无效

[英]Linq result Int error: Specified cast is not valid

Below is my code: 以下是我的代码:

   DataTable dt = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {

        dt.Columns.Add("RowId");
        dt.Columns.Add("Amount");

        DataRow row = dt.NewRow();
        row[0] = "1";
        row[1] = "2000";

        dt.Rows.Add(row);

        GetRecord(1);
    }

    protected void GetRecord(int RowId)
    {
        var results = from row in dt.AsEnumerable()
        where row.Field<int>("RowId") == RowId
        select row;

        string FetchedRowId = results.ToArray()[0].ToString();
    }
}

When I use this way it gives error: Specified Cast is not valid in line: 当我使用这种方式时,它会给出错误:指定的Cast在行中无效:

where TableRow.Field<int>("RowId") == RowId TableRow.Field<int>("RowId") == RowId

But when I convert to: 但是当我转换为:

   protected void GetRecord(int RowId)
    {
        var results = from row in dt.AsEnumerable()
        where row.Field<string>("RowId") == RowId.ToString()
        select row;

        string FetchedRowId = results.ToArray()[0].ToString();
    }

it works. 有用。 Why row.Field<int> is not working? 为什么row.Field<int>不起作用?

The problem is that you didn't specify that your columns are int s. 问题是您没有指定列是int You can specify that with the Add(string, Type) method. 您可以使用Add(string, Type)方法指定它。

dt.Columns.Add("RowId", typeof(int));
dt.Columns.Add("Amount", typeof(int));

DataRow row = dt.NewRow();
// whether you add strings or ints here doesn't matter, it's converted
row[0] = "1";
row[1] = 2000;

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

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