Vb.net 为data gridview选择不同的连接字符串

Vb.net 为data gridview选择不同的连接字符串,vb.net,datagridview,sqldataadapter,Vb.net,Datagridview,Sqldataadapter,为什么这不是直截了当的?我有两个数据库,每个数据库都包含一个日志表。我有一个从表中提取数据的存储过程。我在windows窗体上有一个datagridview,还有一个下拉框,用于选择各个数据库的连接字符串。在选择conn字符串时,我希望更改datagridview以在所选数据库中包含日志消息。 我的代码: Select Case cboConnection.Text Case "CP DEV" LogConnectionString = "Data Source=SAMB

为什么这不是直截了当的?我有两个数据库,每个数据库都包含一个日志表。我有一个从表中提取数据的存储过程。我在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

首先,我没有看到你打开你的连接。然后,你得到了一个有点上下

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)

每次我用你的代码替换我的代码时,应该都能很好地工作,但它似乎不会刷新DataGridView。我必须初始化网格吗,或者我还需要做其他事情吗?@DieterStalmann不刷新DataGridView是什么意思?当我运行TS给出的代码时,网格中的数据不会刷新change@DieterStalmann我有一种感觉,你只是添加到现有的表中,而没有清除它。你们看到的是第一个数据,但更低的数据更多。查看我的更新。但我不确定您是如何管理数据集的。我的例子展示了如何正确地加载它Hanks T.S.它现在工作得很好(不幸的是我不能投票支持你的评论,我的“声誉”还不到15岁。对不起)