ExecuteReader()绑定到GridView中

protected void Page_Load(object sender, EventArgs e)
    {
        //创建连接字符串
        string strConn = "data source=localhost;initial catalog=Northwind;user id=sa;password=sa";
        SqlConnection myConn = new SqlConnection(strConn);
        string strSQL = "SELECT Top 5 CategoryID,CategoryName,Description From Categories";
        //创建SqlCommand对象,其SQl文本为strSQL
        SqlCommand myCommand = new SqlCommand(strSQL, myConn);
        myConn.Open();
        myGv.DataSource = myCommand.ExecuteReader();
        myGv.DataBind();
        myConn.Close();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过以下步骤将C#的SqlDataReader绑定到DataGridView: 1. 在窗体设计器添加一个DataGridView控件。 2. 在代码,创建一个SqlConnection对象并打开连接。 3. 创建一个SqlCommand对象,执行查询并返回一个SqlDataReader对象。 4. 使用SqlDataReader对象的Read()方法读取每一行数据,并将数据添加到DataGridView控件。 下面是一个示例代码: ``` using System; using System.Data.SqlClient; using System.Windows.Forms; namespace BindingSqlDataReaderToDataGridView { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // 创建连接和命令对象 SqlConnection conn = new SqlConnection("connection string"); SqlCommand cmd = new SqlCommand("SELECT * FROM myTable", conn); // 打开连接并执行查询 conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); // 将数据添加到DataGridView控件 while (reader.Read()) { dataGridView1.Rows.Add(reader["Column1"], reader["Column2"], reader["Column3"]); } // 关闭连接和DataReader对象 reader.Close(); conn.Close(); } } } ``` 在上面的示例,我们首先创建了一个SqlConnection对象和一个SqlCommand对象。然后,我们打开连接并使用ExecuteReader()方法执行查询并返回一个SqlDataReader对象。接着,我们使用SqlDataReader对象的Read()方法循环读取每一行数据,并将数据添加到DataGridView控件。最后,我们关闭连接和DataReader对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值