简体   繁体   中英

Set connection string using a combobox 'selected' item using C#

I am self-learning C# using Visual Studio 2012 and stuck on a connection problem. Basically, I want to use a combobox to connect to a database based on the users selection.

For example: When the user selects TEST1 this will select the test1 database and TEST2 will enable test2 database..etc

The code I have pieced together uses a button which displays the results from a SQL script through a messagebox . At the moment I cant get this to work as the message box does not display anything.

I commented out the MainConnection() as that was a test to see if the connection was working.

Appreciate if someone could point me in the right direction.

Please see the C# code below:

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 TestDB
{
public partial class Form1 : Form
{
    class ComboItemExample
    {
        public string DisplayString { get; set; }
        public string ConnectionString { get; set; }
        public override string ToString() { return DisplayString; }
    }
    private string currentConnection = "Data Source= np-2 ;Initial Catalog= TESTDB Integrated Security=true";

    public Form1()
    {
        InitializeComponent();

        var firstConnection = new ComboItemExample { DisplayString = "Data Source= np-2 ;Initial Catalog= TESTDB1 Integrated Security=true" };
        comboBox1.Items.Add("TEST1");

        var secondConnection = new ComboItemExample { DisplayString = "Data Source= np-2 ;Initial Catalog= TESTDB2 Integrated Security=true" };
        comboBox1.Items.Add("TEST2");
    }
    public void MainConnection()
    {
        //Make connection to np-2 TESTDB
        //string str = "Data Source= np-hums12 ;Initial Catalog= TESTDB;"
         //+ "Integrated Security=true";
        // ReadOrderData(str);
    }
    public static void ReadOrderData(string currentConnection)
    {
        // Run SQL script

        string queryString = "SELECT *;";  
        using (SqlConnection connection = new SqlConnection(currentConnection))        
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
        }

        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            // call read before accessing data.
            while (reader.Read())
            {
                //display script in message box
                MessageBox.Show(reader.GetValue(1).ToString());
            }
        // close when finished reading.
            reader.Close();
        }
    }

    private void CloseUI_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void ShowData_Click(object sender, EventArgs e)
    {
        MainConnection();
    }

    private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
    {
        if (comboBox1.SelectedIndex <= 0) return;
        var newConnection = ((ComboItemExample)comboBox1.Items[comboBox1.SelectedIndex]).ConnectionString;

        // use "newConnection" as connection string. 
        currentConnection = newConnection;
        using (var connection = new SqlConnection(currentConnection))
        {

        }
    }
  }
}

Assuming your connection strings are correct and functioning, the reason it is displaying nothing is because it is throwing an error with your SQL.

This line is where your mistake lies

string queryString = "SELECT *;";

It is not a valid SQL query, you need to also specify a table. To help in the future, its is often wise to use try-catch statements to help identify potential errors.

For example in your code you could use

using (SqlConnection connection = new SqlConnection(ConnectionString))
{
    SqlCommand command = new SqlCommand(queryString, connection);

    try
    {
        connection.Open();
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            { 
                MessageBox.Show(reader.GetValue(1).ToString());
            }

            //dont need to close the reader as the using statement will dispose of it once finished anyway
        }

    connection.Close();
    }
    catch (Exception ex)
    {
        connection.Close();
        Console.WriteLine(ex.Message);
        //or, depending on the package Debug.WriteLine(ex.Message);
    }
}

This will print out the exception and stop your program locking up too. As it stands, your current one won't throw an error saying nothing was found, but it will throw an SQL exception in the output log but won't give you details. Exeception.Message will give you details, or SqlException.Message can provide SQL related messages.

Edit: In response to the comment you posted (and something I missed previously)

Looking at the way you have added your ComboBox items, you haven't even added the objects that you think you have. From your code, your combobox items will be "TEST1" and "TEST2" - not the connection strings.

Instead, you could add your objects to the box like so

comboBox1.Items.Add(new ComboItemExample() {DisplayString ="TEST1",ConnectionString = "Data Source= np-2 ;Initial Catalog= TESTDB1 Integrated Security=true"});
comboBox1.Items.Add(new ComboItemExample() {DisplayString ="TEST2",ConnectionString = "Data Source= np-2 ;Initial Catalog= TESTDB2 Integrated Security=true"});
comboBox1.DisplayMember = "DisplayString";
comboBox1.ValueMember = "ConnectionString";

Then to retrieve the value from the combobox for your query

string myConnectionVal = comboBox1.SelectedValue.ToString();

The reason you are getting the cast error is because you never assigned the ComboItemExample to the combobox in the first place. With the item adding code above you would be able to do this in the future, but if all you need is a single value from the object, ValueMember is easier to use.

It looks like you're just adding the text value to your comboboxes, but not actually tying the connection string to it. You may be inadvertently passing the values "TEST1" and "TEST2" as connection strings. You should be adding the new variables you're creating in your constructor as the new items, not those strings. Use the Add() that takes an Item as a parameter.

mycombobox.Add(new Item("Test1", firstConnection));

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