Selecting different connection strings for data gridview

岁酱吖の 提交于 2019-12-24 07:29:26

问题


Why is this not straight-forward? I have two databases that contain a log-table each. I have a stored procedure that extracts the data from the table. I have a datagridview on a windows form, and a drop-down box to select the connection string for the respective databases. On selection of the conn string, I want to change the datagridview to contain the log messages in the selected database. My code:

Select Case cboConnection.Text
    Case "CP DEV"
        LogConnectionString = "Data Source=SAMBAR.gofast.com;Initial Catalog=CPDev;User ID=gofastconfig;Password=gofastdev;" 
    Case "CP LIVE"
        LogConnectionString = "Data Source=SAMBAR.gofast.com;Initial Catalog=CPLive;User ID=gofastconfig;Password=gofastlive;"
End Select

Dim cmd As New SqlCommand("dbo.getLogMessages") 
Using con As New SqlConnection(LogConnectionString)
    Using sda As New SqlDataAdapter() 
        cmd.Connection = con 
        cmd.CommandType = CommandType.StoredProcedure
        sda.SelectCommand = cmd
        sda.Fill(Me.CustomerPulseDBDataSet1)
        con.Close()  
        gridLog.DataSource = Me.CustomerPulseDBDataSet1.Tables(0)
    End Using
End Using

回答1:


First, I don't see you open your connection. Then, you got it a bit up side down...

Using con As New SqlConnection(LogConnectionString)
    con.Open()
    Using cmd As New SqlCommand("dbo.getLogMessages", con)
        cmd.CommandType = CommandType.StoredProcedure

        Using da As New SqlDataAdapter(cmd) 
            ' We need to clear out old data before reloading if same DS instance used
            If Me.CustomerPulseDBDataSet1.Tables.Count > 0 Then
                Me.CustomerPulseDBDataSet1.Tables.Clear()
            End If
            da.Fill(Me.CustomerPulseDBDataSet1)
        End Using  

    End Using
    con.Close()
End Using 

gridLog.DataSource = Me.CustomerPulseDBDataSet1.Tables(0)

Should work perfectly every time



来源:https://stackoverflow.com/questions/30179691/selecting-different-connection-strings-for-data-gridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!