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.
- private void txtPassword_Leave(object sender, EventArgs e)
- {
-
- try
- {
- var con = new SqlConnection(string.Format("Data Source={0};User ID={1};Password={2};", txtServerName.Text, txtUserId.Text, txtPassword.Text));
- var comm = new SqlCommand("SELECT name FROM master.sys.databases", con)
- {
- CommandType = CommandType.Text
- };
- con.Open();
- var objreader = comm.ExecuteReader();
- while (objreader.Read())
- {
- txtDatabase.AutoCompleteCustomSource.Add(objreader["name"].ToString());
- }
- con.Close();
- } catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
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.
- private void txtDatabase_Validating(object sender, CancelEventArgs e)
- {
- txtConnString.Text = string.Format("Data Source={0};Initial Catalog={1};User Id={2};Password={3}", txtServerName.Text, txtDatabase.Text, txtUserId.Text, txtPassword.Text);
- }
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.