为数据gridview选择不同的连接字符串

时间:2021-12-02 14:37: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:

为什么这不直截了当?我有两个数据库,每个数据库都包含一个日志表。我有一个存储过程从表中提取数据。我在Windows窗体上有一个datagridview,还有一个下拉框,用于选择各个数据库的连接字符串。在选择conn字符串时,我想更改datagridview以包含所选数据库中的日志消息。我的代码:

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 个解决方案

#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

应该每次都完美

#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

应该每次都完美