[英]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.