在VB表单上显示SQL查询结果

时间:2011-10-17 12:31:42

标签: vb.net sql-server-2008 ado.net

我在表单上显示“select *”查询结果时遇到问题。这是我的代码:

           Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As     System.EventArgs) Handles Button2.Click

    myconnection = New SqlConnection("server=PARTH-PC\SQLEXPRESS;uid=sa;pwd=parth;database=college")

    myconnection.Open()
    mycommand = New SqlCommand("SELECT * from [demo3]",myconnection)
    Dim mySqlDataAdapter As New SqlDataAdapter(mycommand)
    Dim mydsStudent As New DataSet()

    DataGridView2.DataSource = mydsStudent
    Me.Controls.Add(DataGridView2)
    ra = mycommand.ExecuteNonQuery()
    MessageBox.Show("Data displayed" & ra)

    myconnection.Close()
End Sub

但是当我编写此代码并运行我的表单时,我无法看到我的表单上显示的数据库表中存在任何记录。我在表单上插入了一个DataGridView。我应该对我的代码做些什么改变?任何人都可以帮助我吗?

提前致谢

1 个答案:

答案 0 :(得分:7)

当您使用DataAdapter时,需要调用Fill()方法来填充DataSet/DataTable。初始化DataSet后,请拨打此电话:

mySqlDataAdapter.Fill(mydsStudent)

另外,请取出ExecuteNonQuery()来电。

编辑:尝试这样的事情。

Dim myconn As New SqlConnection(yourConnectionStringHere)
Dim myTable As New DataTable()
Dim myCmd As New SqlCommand()
myCmd.Connection = myconn
myCmd.CommandText = "select * from demo3"

Dim myAdapater As New SqlDataAdapter(myCmd)
myAdapter.Fill(myTable)

DataGridView2.DataSource = myTable