简体   繁体   中英

Function to load data in MySQL

I created a function to load data from MySQL using VB.NET however I have received the following error:

Fill : la propriété SelectCommand.Connection n'a pas été initialisée.

I don't know what I'm doing wrong.

This is my code:

Private Sub ShowDataExam(ByVal DGV As DataGridView, ByVal TBL As String, ByVal CNN As MySqlConnection )
    OpenConnexion()
    Using DA As New MySqlDataAdapter("SELECT * FROM [" & TBL & "]", CNN)
        Dim DTEL As New DataTable
        DA.Fill(DTEL)
        DGV.Font = New Font("Arial", 9, FontStyle.Bold)
        DGV.DataSource = DTEL
        CloseConnexion()
    End Using
End Sub

And this how to use it:

ShowDataExam(DataGridView1,"examiners",DataConnexion.Conn)

I'm not sure why exactly you are passing through your DataGridView as a parameter however consider changing it to ByRef :

Specifies that an argument is passed in such a way that the called procedure can change the value of a variable underlying the argument in the calling code.

ByRef differs slightly from ByVal :

Specifies that an argument is passed in such a way that the called procedure or property cannot change the value of a variable underlying the argument in the calling code.

This may not actually be an issue if the method is within the form that the DGV resides on however then you don't need to pass it as a parameter. Like I said I'm not sure why it is you're passing it as a parameter.

As for the error you are getting (translated to English):

The SelectCommand.Connection property has not been initialized.

I would consider a slight change to your code as I feel in this case you don't actually need a MySqlDataAdapter , instead use MySqlCommand :

OpenConnexion()
Using cmd As New MySqlCommand("SELECT * FROM [" & TBL & "]", CNN)
    Dim DTEL As New DataTable
    DTEL.Load(cmd.ExecuteReader)

    DGV.Font = New Font("Arial", 9, FontStyle.Bold)
    DGV.DataSource = DTEL

    CloseConnexion()
End Using

Try to change your code as :

Private Sub ShowDataExam(ByVal DGV As DataGridView, ByVal TBL As String, ByVal CNN As MySqlConnection )
    OpenConnexion() 
    Dim cmd As New MySqlCommand("SELECT * FROM [" & TBL & "]", CNN)
    Dim DA As New MySqlDataAdapter(cmd)
    DA.SelectCommand = cmd
    Dim DTEL As New DataTable
    DA.Fill(DTEL)
    DGV.Font = New Font("Arial", 9, FontStyle.Bold)
    DGV.DataSource = DTEL
    CloseConnexion()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM