DataReader 绑定DataGridView的方式

DataReader 绑定DataGridView有两种方式


第一种:借助于BindingSource
sqlDataReader Sdr=通过查询函数得到的sqlDataReader类型的数据;
BindingSource Bs=new BindingSource() ;
Bs.DataSource=Sdr;
DataGridView.DataSource=Bs;

 

第二种:借助DataTable
sqlDataReader Sdr=通过查询函数得到的sqlDataReader类型的数据;
DataTable Dt=new DataTable();
Dt.Load(Sdr);
DataGridView.DataSource=Bs;

 

获取DataGridView的选择的行
例如将选择的行的第一列的值转换成string的类型并赋给Num
string Num=Convert.ToString(DataGridView[0,DataGridView.CurrentCell.RowIndex].Value);
这样选中的行的第一列就转换成了string类型的数据,可以通过SQL语句进行其他的操作。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值