在C#中将数据绑定到DataGridView

时间:2013-02-21 11:25:13

标签: c# datagridview sqlcommand

我有一个包含IDName列的表格,我希望在ID中显示NameDataGridView中的Textbox 1}}当我输入ID并单击搜索按钮时,datagridview显示特定记录。在搜索Button中,我有以下代码,但它提供了错误

con.Open();
Sqlcommand cmd = new Sqlcommand("Select * from Registration where ID = '"+textBox1.Text+"'")
sqldatareader reader = cmd.Executereader();
if (reader.HasRows)
{
          datagridview1.DataSource = reader.GetSqlValues()
 }

如何将数据绑定到datagridview?

2 个答案:

答案 0 :(得分:1)

而不是数据阅读器使用dataSet

con.Open();

Sqlcommand cmd = new Sqlcommand("Select * from Registration where ID = '"+textBox1.Text+"'");

sqlDataAdapter1 = new SqlDataAdapter();

sqlDataAdapter1.SelectCommand = cmd;

DataSet ds = new DataSet();

sqlDataAdapter1.Fill(ds);

datagridview1.DataSource = ds.table(0);

这会对你有所帮助

答案 1 :(得分:0)

con.Open();
Sqlcommand cmd = new Sqlcommand("Select * from Registration where ID= '"+textBox1.Text+"'",con);
sqldatareader reader = cmd.Executereader();
if (reader.HasRows)
{
          datagridview1.DataSource = reader.GetSqlValues();
 }