以下是我的代码:
当我使用这种方式时,它会出现错误:在以下行中指定的转换无效:
其中
但是当我进行转换后:
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();
}
}
当我使用这种方式时,它会出现错误:在以下行中指定的转换无效:
其中
TableRow.Field<int>("RowId") == RowId
但是当我进行转换后:
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();
}
它能够工作。为什么row.Field<int>
无法工作?
row[0]
将尝试自动将该值转换为正确的数据类型,这是一种非常“隐晦”的特性 :| - King Kingstring
。 - King KingGetRecord(1)
部分没问题,只是当你使用row.Field<int>("RowId")
时,列的类型 (string
) 和你尝试获取它的类型 (int
) 之间的不匹配导致了问题。 - Tim S.