C#编程代码如何从数据库中查询并把查询结果显示在dataGridView?

2024-10-31 06:14:51
推荐回答(3个)
回答1:

最简单的

写一个数据查询类.然后调用xx.chaxun方法

窗体代码写以下这些就可以了

sql = "select * from xxxx";

Datatable dt = xx.chaxun(sql);

datagridview1.DataSource = dt;

记得将datagridview里面的字段与表中的字段相关联

Dateset 或DataTable或集合进行数据绑定,如有什么问题,请继续追问 private DataSet ds = new DataSet();

private SqlDataAdapter adapter = new SqlDataAdapter();//创建数据适配器

SqlCommand com = new SqlCommand("select TeacGuid, TeacName as 姓名,TeacSex as 性 别,TeacSalary as 工资,TeacRemark as 备注 from Teachers", DBHelper.con);

adapter.SelectCommand = com;

adapter.Fill(ds, "Teachers");//将按照条件查出来的Teachers表中信息填充到ds中

this.dataGridView1.DataSource = ds.Tables["Teachers"]; 附上一段用DataSet实现的代码。

回答2:

Dateset 或DataTable或集合进行数据绑定,如有什么问题,请继续追问 private DataSet ds = new DataSet();
private SqlDataAdapter adapter = new SqlDataAdapter();//创建数据适配器
SqlCommand com = new SqlCommand("select TeacGuid, TeacName as 姓名,TeacSex as 性 别,TeacSalary as 工资,TeacRemark as 备注 from Teachers", DBHelper.con);
adapter.SelectCommand = com;
adapter.Fill(ds, "Teachers");//将按照条件查出来的Teachers表中信息填充到ds中
this.dataGridView1.DataSource = ds.Tables["Teachers"]; 附上一段用DataSet实现的代码,如果有疑问,请继续追问,如果没有,请采纳,万分感谢

回答3:

使用Dateset  或DataTable或集合进行数据绑定,如有什么问题,请继续追问  private DataSet dt = new DataSet();

private SqlDataAdapter adapter = new SqlDataAdapter();//创建数据适配器

SqlCommand com = new SqlCommand("select TeacGuid, TeacName as 姓名,TeacSex as 性     别,TeacSalary as 工资,TeacRemark as 备注 from Teachers", DBHelper.con);

adapter.SelectCommand = com;

adapter.Fill(dt, "Teachers");//将按照条件查出来的Teachers表中信息填充到dt中