我有一些代码用数据库名称填充组合框。然后我有一个按钮,将名称保存回My.Settings并创建连接字符串。
这在很大程度上是有效的。如果我选择一个数据库,它将在我的表单中显示该数据库的正确信息,然后如果我返回到我的数据库选择器并执行相同操作,它仍将显示正确的设置。
问题是,我有一个重新加载datagridview sub,它重新填充网格。如果我选择一个数据库,然后退出并选择另一个,然后运行reload sub,它将从其他数据库中提取设置。即使它最初启动时,它在表单中也有正确的数据库信息。
我尝试了My.Settings.Reset和My.Settings.Save无济于事。
以下是一段代码:
Dim strDatabase As String = My.Settings.Database
Dim strDatabaseCon As String = My.Settings.DatabaseCon
Public Sub Loadcombobox()
My.Settings.Reset()
My.Settings.Save()
Try
Dim con As New SqlConnection(" Data Source=******\SQLEXPRESS; Initial Catalog =" & strDatabase & "; Integrated Security=true")
con.Open()
Dim cmd As New SqlCommand("Select * From sys.databases Where database_id > 4", con)
Dim read As SqlDataReader = cmd.ExecuteReader()
While read.Read()
ComboBox1.Items.Add(read.Item(0))
End While
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox1.Text = "" Then
MessageBox.Show("Please select a customer")
Else
My.Settings.Database = ComboBox1.Text
strDatabase = My.Settings.Database
My.Settings.DatabaseCon = "Data Source=******\SQLEXPRESS; Initial Catalog =" & strDatabase & "; Integrated Security=true"
'Here we redeclare the strDatabaseCon = My.Settings.DatabaseCon
strDatabaseCon = My.Settings.DatabaseCon
My.Settings.Save()
Mainform.Show()
Me.Hide()
End If
End Sub
此子表单的格式不同,导致datagridview从第一个数据库填充。
Sub ReloadRecords()
Try
FillDataGrid("SELECT * FROM Change_Control order by [DateOfChange] desc", dgvData)
dgvData.Columns(0).Visible = False
dgvData.Columns(1).Width = 200 ''Date of Change''
dgvData.Columns(1).HeaderCell.Value = "Date Of Change"
dgvData.Columns(2).Width = 200 ''Name''
dgvData.Columns(2).HeaderCell.Value = "Who Made the Change"
dgvData.Columns(3).Width = 470 ''Change made''
dgvData.Columns(3).HeaderCell.Value = "Change Made"
dgvData.Columns(4).Visible = False
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
End Try
End Sub
这是FillDataGrid函数
Dim strDatabaseCon As String = My.Settings.DatabaseCon
Public Function FillDataGrid(ByVal Sqlstring As String, ByVal MyDataGrid As DataGridView)
Dim SQLCon As New SQLConnection(strDatabaseCon)
Dim SQLAdapter As New SqlDataAdapter()
Dim myDataset As New DataSet()
SQLCon.Open()
Try
SQLAdapter.SelectCommand = New SqlCommand(Sqlstring, SQLCon)
SQLAdapter.Fill(myDataset)
MyDataGrid.DataSource = myDataset.Tables(0)
Catch ex As Exception
End Try
SQLCon.Close()
SQLAdapter.Dispose()
myDataset.Dispose()
Return True
End Function
答案 0 :(得分:0)
不是很好的修复,但它解决了我的问题。
问题是我的FillDataGrid功能。不知道它的哪一部分,但我创建了一个新的功能,它现在没有用以前选择的数据库填充网格。
Public Sub DisplayRecords()
Try
Dim da = New SqlDataAdapter("SELECT * from Change_Control order by [DateOfChange] desc", strDatabaseCon)
dsetAssets = New DataSet
da.Fill(dsetAssets, "Change_Control")
dgvData.DataSource = dsetAssets.Tables("Change_Control").DefaultView
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
End Try
End Sub