主题:如何把数据库查询出来的数据放进datagridview中
jl7733
[专家分:0] 发布于 2009-04-11 14:34:00
如何把数据库查询出来的数据放进datagridview中,要详细代码!在线等
回复列表 (共2个回复)
沙发
zxfzxfzxf12345 [专家分:0] 发布于 2009-04-25 01:47:00
private void btnSelcet_Click(object sender, EventArgs e)
{
string strSelect = this.txtSelect.Text.Trim();
string StrGuanjzi = this.txtGuanjz.Text.Trim();
string cmd= "";
if ((txtSelect.Text == "") || (txtGuanjz.Text == ""))
{
MessageBox.Show("查询,关键字不能为空!", "提示!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
switch (strSelect)
{
case "序号":
cmd = "Select * from PensonlInformation Where id='" + StrGuanjzi + "'";
break;
case "姓名":
cmd = "Select * from PensonlInformation Where name='" + StrGuanjzi + "'";
break;
case "性别":
cmd = "Select * from PensonlInformation Where sex='" + StrGuanjzi + "'";
break;
}
string conString = ConfigurationSettings.AppSettings["ConnectionString"]; //"server =(local) ;database=data_base;User Id = sa;pwd=123456"
SqlConnection con = new SqlConnection(conString);
try
{
con.Open();
SqlDataAdapter AdapterSelect = new SqlDataAdapter(cmd, con);
//创建DataTable对象实例
DataTable dt = new DataTable();
AdapterSelect.Fill(dt);
//填冲控件
dataGridView1.DataSource = dt.DefaultView;
}
finally
{
con.Close();
}
}
}
板凳
恋伊无名指 [专家分:30] 发布于 2009-05-09 18:00:00
先把查询出来的数据放到一个DataTable中,然后将DataGridView的数据源设置成DataTable即可。
SqlConnection conn=new SqlConnection();//省略,连接数据库
SqlCommand cmd=new SqlCommand(查询语句,conn);
SqlDataAdapter sda=new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
dt.Clear();
sda.Fill(dt);
dataGridView1.DataSource=dt;
我来回复