首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用组合框“selected”项使用C#设置连接字符串

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

Stack Overflow用户
提问于 2017-01-04 00:17:09
回答 2查看 871关注 0票数 0

我正在使用Visual Studio2012自学C#,但遇到了一个连接问题。基本上,我希望使用combobox根据用户的选择连接到数据库。

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

我拼凑的代码使用了一个按钮,该按钮通过messagebox显示来自SQL脚本的结果。目前我不能让这个工作,因为消息框没有显示任何东西。

我注释掉了MainConnection(),因为它是用来测试连接是否正常工作的。

如果有人能给我指出正确的方向,我将不胜感激。

请参考下面的C#代码:

代码语言:javascript
复制
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))
        {

        }
    }
  }
}
EN

回答 2

Stack Overflow用户

发布于 2017-01-04 00:30:19

假设您的连接字符串正确且正常工作,则它不显示任何内容的原因是因为它抛出了SQL错误。

这一行就是您的错误所在

代码语言:javascript
复制
string queryString = "SELECT *;";

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

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

代码语言:javascript
复制
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”,而不是连接字符串。

相反,您可以将对象添加到框中,如下所示

代码语言:javascript
复制
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";

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

代码语言:javascript
复制
string myConnectionVal = comboBox1.SelectedValue.ToString();

出现cast错误的原因是,您从一开始就没有将ComboItemExample分配给组合框。有了上面添加代码的项目,您将来就可以做到这一点,但如果您只需要对象中的单个值,则ValueMember更容易使用。

票数 0
EN

Stack Overflow用户

发布于 2017-01-04 00:36:54

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

代码语言:javascript
复制
mycombobox.Add(new Item("Test1", firstConnection));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41447750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档