【发布时间】:2013-03-27 11:33:14
【问题描述】:
我想对 Datatable 进行 LINQ 查询以选择具有特定 ID 的名称,但它返回名称的长度而不是字符串,这里是一些示例代码:
private void btnShow(object sender, EventArgs e)
{
DataTable CL = new DataTable();
DataRow rt;
CL.Columns.Add(new System.Data.DataColumn("ID", typeof(string)));
CL.Columns.Add(new System.Data.DataColumn("Name", typeof(string)));
for (int i = 0; i< dataGridView1.Rows.Count; i++)
{
rt = CL.NewRow();
rt[0] = dataGridView1.Rows[i].Cells[0].Value.ToString();
rt[1] = dataGridView1.Rows[i].Cells[1].Value.ToString();
CL.Rows.Add(rt);
}
var results = from myRow in CL.AsEnumerable()
where myRow.Field<string>("ID") == "1"
select myRow.Field<string>("Name").ToString();
dataGridView2.DataSource = results.ToList();
}
提前感谢
【问题讨论】:
-
你的数据表里有什么内容?
-
只有两列 ID 和 Names
-
@user2102572 我说的是内容,不是结构:)
-
看不到问题中的内容。
CL在哪里填充?同样发布,可能在填充数据表时出错。 -
您没有发布全部代码,
DataTable是如何填充的?在您点击查询并使用您的内容更新问题之前,您能否在调试中查看 DataTable。您发布的内容将得到一个IEnumerable<string>,其中每个都是该列的值。有人会怀疑长度值在Name列中。