类型转换出错了

shijies 2021-02-01 09:44:18
以下代码不能将查询结果显示到dataGridView1,dataGridView1.DataSource = query.ToList; 有错误,请赐教。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Dept", typeof(string));
DataRow dr = dt.NewRow();
dr["Id"] = 8866;
dr["Name"] = "Jack";
dr["Dept"] = "技术部";
dt.Rows.Add(dr);


var query = from r in dt.AsEnumerable()
select new
{
name = r["Name"].ToString(),
dept = r["Dept"].ToString()
};
foreach (var item in query)
{
richTextBox1.Text += "姓名:" + item.name + "部门:" + item.dept + "\n";
}
dataGridView1.DataSource = query.ToList; //这里出错了
}
}
}


CS0428 无法将方法组“ToList”转换为非委托类型“object”
...全文
2776 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
你这个编译应该通过不了,query.tolist()才生成数据
S15867191120 2021-02-01
  • 打赏
  • 举报
回复
dataGridView1.DataSource = query.ToList(); //这里出错了
  • 打赏
  • 举报
回复
引用 3 楼 shijies 的回复:
改了还是不行: 错误 CS1061 “EnumerableRowCollection<<anonymous type: string name, string dept>>”未包含“tolist”的定义,并且找不到可接受第一个“EnumerableRowCollection<<anonymous type: string name, string dept>>”类型参数的可访问扩展方法“tolist”(是否缺少 using 指令或程序集引用?)
注意大小写。。。你原本的对的就是少了括号,有括号才是方法,没有只是属性。。 dataGridView1.DataSource = query.ToList();
shijies 2021-02-01
  • 打赏
  • 举报
回复
改了还是不行: 错误 CS1061 “EnumerableRowCollection<<anonymous type: string name, string dept>>”未包含“tolist”的定义,并且找不到可接受第一个“EnumerableRowCollection<<anonymous type: string name, string dept>>”类型参数的可访问扩展方法“tolist”(是否缺少 using 指令或程序集引用?)

8,494

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 LINQ
社区管理员
  • LINQ
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧