vb.net 从数据库读取并填充DataTable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10844358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:07:34  来源:igfitidea点击:

Read from database and fill DataTable

vb.netado.netdatatable

提问by Bramenath

I'm getting a set of data by a DataReaderand assigning to a string. Now I need to fill the DataTablecolumns with the query fields. The DataTableis connected to a grid to display the filled data.

我通过 a 获取一组数据DataReader并分配给一个字符串。现在我需要DataTable用查询字段填充列。将DataTable被连接到电网以显示填充数据。

query is :

查询是:

strSQL = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee

DataTablecolumns are EmpCode, EmpID, EmpName.

DataTable列是EmpCode, EmpID, EmpName.

I need to read the query and assign to the columns of DataTableand fill the table. I have tried as below but i dont get the proper output,

我需要阅读查询并分配给表的列DataTable并填充表。我试过如下,但我没有得到正确的输出,

Me.DtShifts.Tables("NonAllocated").Clear()
Me.DtShifts.Tables("NonAllocated").Load(dr)

回答by SSS

Connection object is for illustration only. The DataAdapter is the key bit:

连接对象仅用于说明。DataAdapter 是关键位:

Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
  cnn.Open()
  Using dad As New SqlDataAdapter(strSql, cnn)
    dad.Fill(dtb)
  End Using
  cnn.Close()
End Using

回答by Snookger Isolation

Private Function LoaderData(ByVal strSql As String) As DataTable
    Dim cnn As SqlConnection
    Dim dad As SqlDataAdapter

    Dim dtb As New DataTable
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        dad = New SqlDataAdapter(strSql, cnn)
        dad.Fill(dtb)
        cnn.Close()
        dad.Dispose()
    Catch ex As Exception
        cnn.Close()
        MsgBox(ex.Message)
    End Try
    Return dtb
End Function