简体   繁体   中英

Connect to SQL DB via Textbox

So I am trying to use a connection string that is pasted into a textbox to connect to a db when the connect button is clicked. I have the following code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace SQLTool
{
    public partial class SQLTool : Form
    {
        public SQLTool()
        {
            InitializeComponent();

        }
        public static SqlConnection myConnection = null;

        public void Connection()
        {
            myConnection = new SqlConnection(DBConnectionBox.Text);
            //myConnection.Open();
        }


        private void DBConnectBtn_Click(object sender, EventArgs e)
        {
            SqlConnection myConnection = new SqlConnection(DBConnectionBox.Text.ToString());
            myConnection.ConnectionString = "Data Source=ServerName;" + "Initial Catalog=DatabaseName;" + "User ID=UserName;" + "Password=Password";
            myConnection.Open();

            if (myConnection !=null && myConnection.State == ConnectionState.Closed)
            {
                MessageBox.Show("SUCCESS!!");
            }


        }




    }
}

I have added a picture of my form. The combobox I will be adding data from the db I connect to. So any help on that would be appreciated as well. Form Picture

Maybe someone can point me into the right direction. The if statement was just for testing if I was connecting to the db. This is my first time trying something like this so I am a bit lost. Any help would be greatly appreciated.

UPDATE:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace SQLTool
{
    public partial class SQLTool : Form
    {
        public SQLTool()
        {
            InitializeComponent();

        }
        public static SqlConnection myConnection = null;




        private void DBConnectBtn_Click(object sender, EventArgs e)
        {

            try
            {
                var myConnection = new SqlConnection(DBConnectionBox.Text);
                myConnection.Open();
                if (myConnection.State == ConnectionState.Open)
                {
                    var sqlCmd = new SqlCommand("SELECT * FROM Menu", myConnection);
                    var sqlReader = sqlCmd.ExecuteReader();

                    while (sqlReader.Read())
                        ClientComboBox.Items.Add(sqlReader["Name"].ToString());

                    //MessageBox.Show("SUCCESS!!");


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Failed to connect. Message {ex.Message}");
            }


        }


    }
}

The only thing left to do is to populate the datagridview with a SQL Query that is ran depending on what I pick in the combobox.

Ok guys, new problem:

private void ClientComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {

        try
        {
            var myConnection = new SqlConnection(DBConnectionBox.Text);
            myConnection.Open();
            if  (myConnection.State == ConnectionState.Open)
            {
                var Cmd = new SqlCommand("SELECT * FROM Menu WHERE Name ='" + ClientComboBox.Text + "';");
                var Reader = Cmd.ExecuteReader();

                while(Reader.Read())
                {
                    SqlDataAdapter sqlDataAdap = new SqlDataAdapter(Cmd);

                    DataSet dtRecord = new DataSet();
                    sqlDataAdap.Fill(dtRecord);
                    ClientInfoDGV.DataSource = dtRecord;

                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

When I click on a combobox item something is populated in the datagridview (ClientInfoDGV). It goes straight to the catch.

You should not reinitialize ConnectionString property of myConnection object, since it is already initialized.

Also notice that you should check for myConnection.State == ConnectionState.Open in order to determine where connection is opened or not.

You can try following

public static SqlConnection myConnection = null;
private void DBConnectBtn_Click(object sender, EventArgs e)
{
  try
  {
    var myConnection = new SqlConnection(DBConnectionBox.Text);
    myConnection.Open();
    if (myConnection.State == ConnectionState.Open)
      MessageBox.Show("SUCCESS!!");
  }
  catch (Exception ex)
  { MessageBox.Show($"Failed to connect. Message {ex.Message}"); }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM