How to set a table adapter's connection string (to one that is dynamically set)
I just inherited the role of "Database Guy" from another developer who is no longer with the company, so please forgive me if I sound particularly noobish.
The application is a VB.NET 4 application.
The DB connection string for our table adapters was a string in my.settings (My.Settings.DBConnectionString) that is being set at runtime. When I had to modify the table adapters they couldn't see any data in My.Settings.DBConnectionString and thus did not allow me to edit them until I set a "real" (or hard-coded) connection string. Now I want to change it back to the dynamically set one, but Visual Studio doesn't seem to want to let me do that. I believe I've found the spot in the auto-generated code behind the .xsd file to be able to change the connection string for a particular table adapter, but if I do that will bad things happen? Or is there some other mech开发者_开发知识库anism for changing a table adapter's connection string other than the properties pane on the side of Visual Studio that I am not aware of?
Just as a secondary question, are there bad / not-best practices going on here?
Thanks!
Here is how I solved the problem of changing the connection string at runtime. Hope this helps.
In my settings, I have 2 entries
I have a Dataset called DataSet1
I have 3 forms called Form1, Form2 and Form3
Form1 has the following controls
And the following code
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
Form2 has the following controls
with the following code
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
and Form3 has the following controls
with the following code
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
This sounds like your table adapter's connection string is being set by an application setting?
I'm not sure quite what you mean by setting them dynamically, but it sounds like you may have come across the often disputed (I know, citation needed...) feature that means you cannot set application scope settings at runtime. This is because the auto-generated classes provide readonly properties for your app settings. User scope settings can be changed (see previous link for details).
There is a post here discussing changing application settings which may be of use.
If you do need to change application settings at runtime, it may be worth implementing your own settings mechanism which uses XML, the Registry, or something else to store, retrieve, and change settings.
Hope that helps
EDIT:
Suddenly occurred to me that I hadn't read your question properly. Not only is your connection string probably derived from an application setting, but perhaps your table adapter is bound to that connection string? If so, see this post which explains how you can inject/change the connection string for table adapters. Seems like a bit of a hack to me, but it should work.
Here is how I updated a Connectionstring from a INI file with a Module in VB that shows a slightly different way to update the connectionstring.
It allows the client to update the connection from a form in the application. The textboxes on the form are tied to the Public strings in the module. Pressing the save button on the form calls the savedbsetup method in the module. Then the time the app is launched, it loads the new settings from the created INI file
Imports System.Configuration
Imports System.Environment
Imports System.IO
Module SetupOptions
Public DBJacksServer As String = "CSTDesktop1\SQLExpress"
Public DBJacksCatalog As String = "PreJacks"
Public DBJacksUserName As String = "sa"
Public DBJacksPassword As String = "dba"
Public appData As String = $"{GetFolderPath(SpecialFolder.ApplicationData)}/CSTSoftware/Jacks"
Public DBJacksSetUpFile As String = $"{appData}/DBJackssetup.ini"
Public DBConnectionStringSettingsName As String = "Jacks.My.MySettings.PreJacksConnectionString"
Public Sub SaveDBSetup()
Try
If Not Directory.Exists(appData) Then
Directory.CreateDirectory(appData)
End If
If File.Exists(DBJacksSetUpFile) Then
File.Delete(DBJacksSetUpFile)
End If
Using sw As StreamWriter = New StreamWriter(DBJacksSetUpFile)
sw.WriteLine(DBJacksServer)
sw.WriteLine(DBJacksCatalog)
sw.WriteLine(DBJacksUserName)
sw.WriteLine(DBJacksPassword)
End Using
Catch ex As Exception
MessageBox.Show($"Failed to Save DB Settings With this Error: {ex.Message}")
End Try
End Sub
Public Sub LoadDBSetup()
Try
If File.Exists(DBJacksSetUpFile) Then
Using sr As StreamReader = New StreamReader(DBJacksSetUpFile)
DBJacksServer = sr.ReadLine()
DBJacksCatalog = sr.ReadLine()
DBJacksUserName = sr.ReadLine()
DBJacksPassword = sr.ReadLine()
End Using
SetDBJacksConnection()
End If
Catch ex As Exception
MessageBox.Show($"Failed to Load DB Settings With this Error: {ex.Message}")
End Try
End Sub
Public Function GetDBJacksConnection() As String
'If File.Exists(DBJacksSetUpFile) Then
' Return $"Data Source={DBJacksServer};Initial Catalog={DBJacksCatalog};Persist Security Info=True;User ID={DBJacksUserName};Password={DBJacksPassword}"
'Else
Return ConfigurationManager.ConnectionStrings(DBConnectionStringSettingsName).ConnectionString
'End If
End Function
Public Sub SetDBJacksConnection()
Dim config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim csSection = config.ConnectionStrings
csSection.ConnectionStrings(DBConnectionStringSettingsName).ConnectionString = $"Data Source={DBJacksServer};Initial Catalog={DBJacksCatalog};Persist Security Info=True;User ID={DBJacksUserName};Password={DBJacksPassword}"
config.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("connectionStrings")
End Sub
End Module
精彩评论