我只使用sqldatareader和datagridview获得列标题

时间:2013-09-03 11:17:16

标签: vb.net sqldatareader

我有SQL Server 2008表达数据库和table并使用VB 2010表达。

我尝试使用sqldatareader从该表中读取,但我在datagridview中只有一行包含列标题,没有数据行。

我做错了什么? (我是新手)。

连接字符串是: Data Source=xxxxxxxxxx\SQLEXPRESS;Initial Catalog=Masteca_Inventory;Integrated Security=True

Dim searchStr As String = ""
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sqlStr As String

Public bindingSource1 As New BindingSource()

connetionString = My.Settings.SQLconnSTR
sqlStr = "SELECT * FROM Piese WHERE " & searchStr  'searchStr is OK I fill it elsewhere
sqlCnn = New SqlConnection(connetionString)

Try
    sqlCnn.Open()
    sqlCmd = New SqlCommand(sqlStr, sqlCnn)

    Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()

    Using sqlReader

        Dim dTable As New DataTable
        dTable.Load(sqlReader)
        bindingSource1.DataSource = dTable

    End Using

    SearchReport.DataGridView1.DataSource = bindingSource1
    'SearchReport is another form

    sqlReader.Close()
    sqlCmd.Dispose()
    sqlCnn.Close()

    SearchReport.Show()

Catch ex As Exception
    MsgBox(ex.ToString)
End Try

1 个答案:

答案 0 :(得分:1)

您不是以组的形式阅读数据(您只获取一个结果)。

您需要调整代码以使用While sqlReader.Read;

实施例

Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()

While sqlReader.Read()
    Try                      
       'Do the work needed 
       rowResult += sqlReader(0) 'This will contain the result script
    Catch ex As Exception
       'Catch exception
    End Try

End While

这样的东西应该有效(我没有测试过代码,但概念是相同的)。

PS - 我强烈建议您调整脚本以添加Where子句和/或所需的列(选择*不是“良好做法”)

希望这有帮助。