问题
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