繁体   English   中英

使用C#使用组合框“选定”项设置连接字符串

[英]Set connection string using a combobox 'selected' item using C#

我正在使用Visual Studio 2012自学C#,但遇到连接问题。 基本上,我想根据用户的选择使用combobox连接到数据库。

例如:当用户选择TEST1这将选择test1数据库,而TEST2将启用test2数据库。

我拼凑的代码使用一个按钮,该按钮通过messagebox显示SQL脚本的结果。 目前,由于消息框未显示任何内容,我无法使其正常工作。

我注释掉MainConnection()因为它是测试以查看连接是否正常工作。

欣赏有人能指出我正确的方向。

请参见下面的C#代码:

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))
        {

        }
    }
  }
}

假设您的连接字符串正确并且可以正常工作,那么它什么也不显示的原因是因为它在SQL中引发了错误。

这行是您的错误所在

string queryString = "SELECT *;";

这不是有效的SQL查询,您还需要指定一个表。 为了将来有所帮助,明智的做法是使用try-catch语句来帮助识别潜在的错误。

例如,您可以在代码中使用

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);
    }
}

这将打印出异常并停止程序锁定。 就目前的情况而言,您当前的用户不会抛出错误,表明什么也没找到,但是它将在输出日志中抛出SQL异常,但不会提供详细信息。 Exeception.Message将为您提供详细信息,或者SqlException.Message可以提供与SQL相关的消息。

编辑:针对您发布的评论(以及我之前错过的内容)

在您添加ComboBox项的方式上,您甚至还没有添加您认为拥有的对象。 从您的代码中,您的组合框项目将为“ TEST1”和“ TEST2”,而不是连接字符串。

相反,您可以像这样将对象添加到框中

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";

然后从组合框中为您的查询检索值

string myConnectionVal = comboBox1.SelectedValue.ToString();

出现ComboItemExample转换错误的原因是,您从未首先将ComboItemExample分配给组合框。 通过上面的项目添加代码,您将来可以执行此操作,但是如果您只需要来自对象的单个值,则ValueMember会更易于使用。

看起来您只是将文本值添加到组合框中,而实际上没有将连接字符串绑定到它。 您可能无意间将值“ TEST1”和“ TEST2”作为连接字符串传递。 您应该将在构造函数中创建的新变量添加为新项,而不是这些字符串。 使用将Item作为参数的Add()。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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