下面是我如何解決在運行時更改連接字符串的問題。希望這可以幫助。
在我的設置,我有2項
我有一個數據集名爲DataSet1的
我有3種形式稱爲Form1上,窗體2和Form3
Form1中有以下控件
而下面的代碼
Public Class Form1
Private Sub GenericoBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles GenericoBindingNavigatorSaveItem.Click
Me.Validate()
Me.GenericoBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DataSet1)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TableAdapterManager.Connection.ConnectionString = My.MySettings.Default._001NewConnectionString
Me.TableAdapterManager.UpdateAll(Me.DataSet1)
Label5.Text = My.MySettings.Default._001NewConnectionString
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
My.MySettings.Default("_001NewConnectionString") = "Data Source=" & TextBox1.Text & "\" &
TextBox2.Text & ";Initial Catalog=001;Persist Security Info=True;User ID=" &
TextBox3.Text & ";Password=" & TextBox4.Text
My.MySettings.Default.Save()
Me.TableAdapterManager.Connection.ConnectionString = My.MySettings.Default._001NewConnectionString
Me.TableAdapterManager.UpdateAll(Me.DataSet1)
Try
Me.GenericoTableAdapter.Fill(Me.DataSet1.generico)
Catch ex As Exception
MessageBox.Show("error Form1")
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim f As New Form2(TableAdapterManager.Connection.ConnectionString)
f.ShowDialog()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim f As New Form3(TableAdapterManager.Connection.ConnectionString)
f.ShowDialog()
End Sub
End Class
窗體2具有以下控制
用下面的代碼
Public Class Form2
Private Sub UtentesBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles UtentesBindingNavigatorSaveItem.Click
Me.Validate()
Me.UtentesBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DataSet1)
End Sub
Public Sub New(ConnectionString As String)
InitializeComponent()
Me.TableAdapterManager.Connection.ConnectionString = ConnectionString
Me.TableAdapterManager.UpdateAll(Me.DataSet1)
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Me.UtentesTableAdapter.Fill(Me.DataSet1.utentes)
Catch ex As Exception
MessageBox.Show("Form2")
End Try
End Sub
End Class
和Form3具有以下控制
用下面的代碼
Public Class Form3
Public Sub New(ConnectionString As String)
InitializeComponent()
Me.TableAdapterManager.Connection.ConnectionString = ConnectionString
Me.TableAdapterManager.UpdateAll(Me.DataSet1)
End Sub
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Me.UtentesTableAdapter.Fill(Me.DataSet1.utentes)
Catch ex As Exception
MessageBox.Show("Form3")
End Try
End Sub
Private Sub UtentesBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles UtentesBindingNavigatorSaveItem.Click
Me.Validate()
Me.UtentesBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DataSet1)
End Sub
End Class