简体   繁体   中英

The DataAdapter doesn't open the connection itself with Fill Method

I'm using next sub to fill combobox by using datatable through dataadapter:

Public Sub Me_Sub_CboFill(ByVal Cbo As ComboBox, ByVal SqlStr As String, ByVal Dm As String, ByVal Vm As String)
    Cbo.DataSource = Nothing
    xAdapter = New MySqlDataAdapter(SqlStr, Conn)
    Dim Dt As New DataTable
    xAdapter.Fill(Dt)

    If Dt.Rows.Count = 0 Then Conn.Close()

    Cbo.DataSource = Dt
    Cbo.DisplayMember = Dm
    Cbo.ValueMember = Vm

End Sub

but I face next MSG:

unable to connect to any of the specified MySQL hosts but when I open the connection manually, it works!!

I know that dataadapter with (Fill) opens and closes the connection itself but I didn't know why that happened with my code.

by the way, I tried many ways to test that but with the same result, like next code:

    dim dt as new datatable
    Dim xx As New MySqlDataAdapter(SqlNat, Conn)
    MsgBox(Conn.State)
    xx.Fill(Dt)

thanks

First of all, the if statement sholdn't be there, and if you still want to use it, then close it with an "end if" or your code won't work. Second if that's a combobox why to state cbo.datasource = nothing??? You want to erase the content? Use cbo.clear() instead and then you can use your data table as a datasource. Also cbo.displaymember = "Dm" you need those quoutes.

If you keep your connection local to the method where it is used you can control when it is closed and disposed with a Using...End Using block. Your connection might have been disposed by another method in the class.

Public Sub Me_Sub_CboFill(ByVal Cbo As ComboBox, ByVal SqlStr As String, ByVal Dm As String, ByVal Vm As String)
    Cbo.DataSource = Nothing
    Dim Dt As New DataTable
    Using Conn As New MySqlConnection("Your conntection string"),
            xAdapter As New MySqlDataAdapter(SqlStr, Conn)
        xAdapter.Fill(Dt)
    End Using
    Cbo.DisplayMember = Dm
    Cbo.ValueMember = Vm
    Cbo.DataSource = Dt
End Sub

I found the problem with my code I put the connection string inside function that I use to check the connection and for that I needed to call the function at least one time to make everything work correctly.

thanks all for all your information best,

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