DYNAMIC CONNECTION STRINGS IN VB.NET

To change the connection string of a typed dataset in vb.net 2005 and also Building a dynamic connection strings in Vb.net. Below are easy ways these can be done.

1. To change the connection string of a typed dataset, add the method below to the setting file. To see the setting.vb file, go the your project properties, on the settings tab, click on the the view code button and there you go.

Private Sub MySettings_SettingsLoaded(ByVal sender As Object, ByVal e As System.Configuration.SettingsLoadedEventArgs) Handles Me.SettingsLoaded

Dim db As New DBConnect

Me.Item("HospitalConnectionString")  =db.returnConnectionString

End Sub

Note: HospitalConnectionString is the name of the connections string as saved in your project settings

Below is the detail of the “returnConnectionString” procedure

Also note that servername, username, database, password are all saved in the settings

Public function returnConnectionString ()as string

Try

client = getClientName()

With My.Settings

If .servername = client Then

If Me.integratedSecurity = False Then

connectionString = "Data source= " & .servername & "; initial catalog= " & .database & ";user id= " & .username & " ;password = " & .password

Else

connectionString = "Data source= " & servername & "; initial catalog= " & database & "; Integrated Security= " & integratedSecurity

End If

Else

connectionString = "workstation id= " & client & " ;Data source= " & servername & " ;initial catalog= " & database & " ;user id= " & username & " ;password = " & password & " ;Integrated Security=" & integratedSecurity & " ; Connect TimeOut=30"

End If

End With

Catch ex As Exception

Msgbox(ex.ToString)

End Try

Return connectonString

End function

——————————

A function to return the name of the current machine(the machine the program is running on)

Public Function getClientName() As String

Dim client As String = ""

client = Dns.GetHostName

Return client

End Function

Saving items in the Settings

Below is code under the save setting buttons

With My.Settings

.Server = Me.txtServer.Text

.Dbase = Me.txtDbase.Text

.UserName = Me.txtUserName.Text

.Password = Me.txtPassWord.Text

.integrated = Me.ChkSecurity.Checked

.Save()

End With

Tags: , , , ,