简体   繁体   English

将数据绑定到C#中的DataGridView

[英]Bind the Data to DataGridView in C#

I have a table with ID and a Name column i want to show the one ID and Name in a DataGridView For Example in Textbox when i enter ID and click search button the datagridview shows the specifc record. 我有一个表IDName栏我想展现一个IDNameDataGridView在示例Textbox ,当我输入ID ,然后点击搜索按钮在DataGridView显示specifc记录。 In Search Button I have following Code but it gives error 在搜索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()
 }

How can i bind the data to datagridview? 如何将数据绑定到datagridview?

Instead of data reader use dataSet : 代替数据读取器,使用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);

This will help you 这对你有帮助

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();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM