如何使用组合框选择的项目设置连接字符串?

时间:2014-02-08 22:29:32

标签: c#

我有两个公共连接字符串。我认为这个方法没用。我希望用户在点击按钮之前可以从组合框中选择连接到数据库。

public partial class Form1 : Form
{
    public string CompanyA = "Data Source=.;Initial Catalog=compA;User ID=sa;Password=**";
    public string CompanyB = "Data Source=.;Initial Catalog=compB;User ID=sa;Password=***";

    public Form1()
    {
        InitializeComponent();
    }
}

我在代码中使用了CompanyA和CompanyB字符串。

using (SqlConnection con = new SqlConnection(CompanyA ))
{
    // do somethings....
}

using (SqlConnection con = new SqlConnection(CompanyB))
{
    // do somethings....
}

如何通过这样的组合框选择连接字符串? (抱歉错误的架构)

private void ConnectButton_Click(object sender, EventArgs e) 
{
    if ( (comboBox1.SelectedItem=="compA") && ( (comboBox2.SelectedItem=="compB") )
    {
        // public string CompanyA = "Data Source=.;Initial Catalog=compA;User ID=sa;Password=**";
        // public string CompanyB = "Data Source=.;Initial Catalog=compB;User ID=sa;Password=**";
    }
}

2 个答案:

答案 0 :(得分:1)

您可以通过覆盖类中的“ToString”方法将任何您想要的内容放入组合框中。一个简单的例子:

class ComboItemExample {
   public string DisplayString { get; set; }
   public string ConnectionString { get; set; }

   public override string ToString() { return DisplayString; }
}

一旦定义了这个,你可以实例化一些并将它们添加到组合框中。该代码如下:

private string currentConnection = "<default connection>";

public Form1() {
   InitializeComponent();

   var firstConnection = new ComboItemExample { DisplayString = "Local Database", ConnectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;" };
   myComboBox.Items.Add(firstConnection);

   var secondConnection = new ComboItemExample { DisplayString = "Other Database", ConnectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;" };
   myComboBox.Items.Add(secondConnection);
}

最后,您希望在用户更改所选项目时使用这些对象。该代码看起来像:

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

  // now use "newConnection" as your connection string. Save in a local member
  //    or pass directly into the call to create the database connection.
  currentConnection = newConnection;
}

应该这样做!我希望这有帮助!

<强>澄清/修改

为了澄清,您可以稍后使用以下代码创建连接:

using (var connection = new SqlConnection(currentConnection)) {
   // use the connection here
}

我还在上面的代码中添加了一个模块变量,以便清楚地声明和设置当前连接字符串的位置。祝你好运!

答案 1 :(得分:0)

您可以进行连接字符串检查

if (this.comboBox1.SelectedText == "compA")
{
    // connect using the companyA connectionstring
}
else
{
    // connect using the companyB connectionstring
}