从SQLReader填充DataGridView [英] Filling a DataGridView from SQLReader

查看:193
本文介绍了从SQLReader填充DataGridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



一个大纲是我从一个SQL数据库中读取一些数据,并且想要在DataGridView中显示它在表单上。我已经确认有数据从数据库返回,但我不确定为什么这不出现。我已经跟随了许多来自互联网的教程,但到目前为止还没有工作



这里是我的代码

  Private Sub PopulateGrid()
Dim Con As New SqlClient.SqlConnection
Dim strCon As String = CropTrackMod.strConn
Dim strCommand As String =select * from客户


尝试
Con.ConnectionString = strCon
Dim Cm As New SqlClient.SqlCommand(strCommand,Con)
Con.Open()
Dim reader As SqlClient.SqlDataReader = Cm.ExecuteReader()

'测试确认收到的数据
reader.Read()
MsgBox(reader.Item(ContactName ))


DataGridView1.AutoGenerateColumns = True
DataGridView1.DataSource = reader
DataGridView1.Refresh()



Catch ex As Exception
MessageBox.Show(ex.Message,Error)

最后
如果Con.State = ConnectionS tate.Open然后
Con.Close()
如果
结束尝试

End Sub

我也尝试实现一个datatable,但是在数据类型
上收到一个转换错误,任何帮助将不胜感激



谢谢你们

解决方案

你不能直接将数据库直接绑定到WinForms中的datagridview。相反,您可以使用读取器加载数据表,并将数据表分配给DataGridView的数据源

  Dim dt = new DataTable() 
dt.Load(reader)
DataGridView1.AutoGenerateColumns = True
DataGridView1.DataSource = dt
DataGridView1.Refresh()


Im a little stuck on some code that im writing

An outline is that i am reading some data in from an SQL database and wantint to display it in a DataGridView on a form. I have confirmed that there is data being returned from the database but am unsure as to why this isnt appearing. I have followed a number of tutorials from the internet but so far non have worked

here is my code

Private Sub PopulateGrid()
    Dim Con As New SqlClient.SqlConnection
    Dim strCon As String = CropTrackMod.strConn
    Dim strCommand As String = "select * from customer"


    Try
        Con.ConnectionString = strCon
        Dim Cm As New SqlClient.SqlCommand(strCommand, Con)
        Con.Open()
        Dim reader As SqlClient.SqlDataReader = Cm.ExecuteReader()

        'test to confirm data received
        reader.Read()
        MsgBox(reader.Item("ContactName"))


        DataGridView1.AutoGenerateColumns = True
        DataGridView1.DataSource = reader
        DataGridView1.Refresh()



    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error")

    Finally
        If Con.State = ConnectionState.Open Then
            Con.Close()
        End If
    End Try

End Sub

i have also tried to implement a datatable but receive a conversion error on the data type any help would be appreciated

thanks guys

解决方案

You can't bind a datareader directly to a datagridview in WinForms. Instead you could load a datatable with your reader and assign the datatable to the datasource of the DataGridView

Dim dt = new DataTable()
dt.Load(reader)
DataGridView1.AutoGenerateColumns = True
DataGridView1.DataSource = dt
DataGridView1.Refresh()

这篇关于从SQLReader填充DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆