在C#中怎么把SQL数据库中查询的结果以表格的形式显示到Windows窗体上,我添加了一个DataGridView控件

2024-11-21 22:20:05
推荐回答(2个)
回答1:

//连接你的数据库
string connstr = "server=.;uid=sa;pwd=sa;database=sc";
using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlsel, conn);
da.Fill(ds, "coust");
DataTable dt = ds.Tables["coust"];
conn.Close();
return dt;

// TODO: 这行代码将数据加载到表“studentDataSet.studentinfo”中。您可以根据需要移动或移除它。
//this.studentinfoTableAdapter.Fill(this.studentDataSet.studentinfo);
//数据绑定
string sqlsel = "select * from studentinfo ";
DataTable dt = bangding(sqlsel);
cmAmend = (CurrencyManager)BindingContext[dt];
this.dataGridView1.DataSource = dt;
this.textBox1.DataBindings.Add("text", dt, "sno");
this.textBox2.DataBindings.Add("text", dt, "sname");
this.textBox3.DataBindings.Add("text", dt, "ssex");
this.textBox4.DataBindings.Add("text", dt, "sage");
this.textBox5.DataBindings.Add("text", dt, "sclass");
this.textBox6.DataBindings.Add("text", dt, "sdept");
this.textBox7.DataBindings.Add("text", dt, "saddress");
this.textBox8.DataBindings.Add("text", dt, "sphone");
this.textBox9.DataBindings.Add("text", dt, "sqq");

回答2:

用DataGridView的DataSource绑定数据集里的数据表就ok了