为数据网格视图选择不同的连接字符串

Selecting different connection strings for data gridview

为什么这不是直截了当的?我有两个数据库,每个数据库都包含一个 log-table。我有一个从 table 中提取数据的存储过程。我在 windows 表单上有一个数据网格视图,还有一个下拉框 select 各个数据库的连接字符串。在连接字符串的 selection 上,我想更改数据网格视图以包含 selected 数据库中的日志消息。 我的代码:

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

首先,我没有看到你打开连接。然后,你把它弄得有点颠倒了......

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)

应该每次都能完美运行