Create Connection String Using Visual Studio Windows Application

Let us create a Windows Forms Application first, and give it a name 'ConnectionStringBuilder'.


Design your form by drag and drop Textboxes for entering ServerName, UserName, Password and display database and ConnectionString.


Double click on txtPassword leave event.


Write the following code on txtPassword_Leave event.

That will connect the SQL Server and fetch the database names.
  1. private void txtPassword_Leave(object sender, EventArgs e)   
  2. {  
  3.     
  4.     try   
  5.     {  
  6.         var con = new SqlConnection(string.Format("Data Source={0};User ID={1};Password={2};", txtServerName.Text, txtUserId.Text, txtPassword.Text));  
  7.         var comm = new SqlCommand("SELECT name FROM master.sys.databases", con)  
  8.         {  
  9.             CommandType = CommandType.Text  
  10.         };  
  11.         con.Open();  
  12.         var objreader = comm.ExecuteReader();  
  13.         while (objreader.Read())   
  14.         {  
  15.             txtDatabase.AutoCompleteCustomSource.Add(objreader["name"].ToString());  
  16.         }  
  17.         con.Close();  
  18.     } catch (Exception ex)   
  19.     {  
  20.         MessageBox.Show(ex.Message);  
  21.     }  
  22. }  
Now, set the txtDatabase AutoCompleteMode = 'SuggestAppend' and AutoCompleteSource = 'CustomSource'. So when user type database name it will auto suggest database name.


Double click txtDatabase Validating Event.


Write the following code in txtDatabase_Validating event for creating connection string value.
  1. private void txtDatabase_Validating(object sender, CancelEventArgs e)  
  2. {  
  3.     txtConnString.Text = string.Format("Data Source={0};Initial Catalog={1};User Id={2};Password={3}", txtServerName.Text, txtDatabase.Text, txtUserId.Text, txtPassword.Text);  
  4. }  
Now, run your application and enter Servername, User Id and Password, it will connect SQL Server and Suggest database name in database textbox, select the database and tab to connection string textbox. It will display the connection String.


Hope you like this tool that will help you to quickly generate the connection string.
Ebook Download
View all
Learn
View all