如何在从组合框中选择任何值时连接到数据库

时间:2011-05-05 05:43:27

标签: c# winforms visual-studio-2008 combobox

我有一个组合框,其中填充了各种数据库名称。我想从组合框中选择任何数据库名称连接到某个数据库。我应该怎么做呢?代码如下..

private void Form1_Load(object sender, EventArgs e)   
      {  XmlDocument doc = new XmlDocument();
     doc.Load("C:\\Documents and Settings\\user\\Desktop\\abc.xml");             XmlNodeList List = doc.SelectNodes("config/dataSources/dataSource");    
         foreach (XmlNode dataSources in List)             
{ comboBox1.Items.Add(dataSources.Attributes["name"].Value.ToString());                    comboBox2.Items.Add(dataSources.Attributes["name"].Value.ToString());      
 }   

    } 

我有另一个带有连接字符串信息的代码

public class DBConnect   
  {        
 string dataSource;    
     string userId;      
   string password;        
 string filepath;          
public DBConnect()       
  {         }     
     public string ConnectionString()  
       {    filepath = ReadRegistry("ConfigFile");     
         XmlDocument doc = new XmlDocument();   
          doc.Load(@filepath);        
      XmlNodeList nodes = doc.SelectNodes
("/config/dataSources/dataSource");        
         foreach (XmlNode node in nodes)  
     {      if (userId.select == node.Attributes["dataSource"].Value)  
               {      dataSource = node.Attributes
["dataSource"].Value;                 
    userId = node.Attributes["userId"].Value;   
        password = node.Attributes["password"].Value;   
        password = Abc.Security.Encryption.Decode(password);
                     break;         

        }       
      }          
   string conn = "Provider=OraOLEDB.Oracle.1;Persist Security Info=False;Password=" + password + ";User ID=" + userId + ";Data Source=" + dataSource + ";";                 return conn;         }          protected string ReadRegistry(string filename)         {             Microsoft.Win32.RegistryKey theKey = Microsoft.Win32.Registry.LocalMachine;             theKey = theKey.OpenSubKey(@"SOFTWARE\Abc, Inc\Abc Marketing");              if (theKey != null)             {                 //string filePath = theKey.GetValue("ConfigFile").ToString();                 filepath = theKey.GetValue(filename).ToString();                 theKey.Close();           
  }    
          return filepath;  
       } 

所以现在我应该如何编写一个代码,从combobox中选择任何数据库名称将我连接到该特定数据库。我是c#的新手,请给我一个解决方案。我应该在哪里加入代码?

2 个答案:

答案 0 :(得分:2)

你可以做到

SqlConnectionStringBuilder builder =
            new SqlConnectionStringBuilder("server=(local);user id=ab; password= a!Pass113;initial catalog=AdventureWorks");
builder.InitialCatalog = (string)comboBox1.SelectedItem;

对于Oracle做

 OracleConnectionStringBuilder builder =
                new OracleConnectionStringBuilder("");//put connection string here
    builder.UserID = (string)comboBox1.SelectedItem;
    OracleConnection conn = new OracleConnection(builder.ConnectionString);
    OracleCommand cmd = new OracleCommand("Select 1 from dual", conn);
    conn.Open();
    int temp = Convert.ToInt32(cmd.ExecuteScalar());
    conn.Close();

希望这个帮助

答案 1 :(得分:2)

好吧,你可以连接你的ComboBox的SelectedIndexChanged event,当它激活时,你可以从ComboBox的SelectedItem property中检索所选的数据库,并在你的连接字符串中使用它连接到你的数据库。

示例
你说你已经有了一个有效的连接字符串。您需要做的就是允许您的用户更改该字符串的DataSource部分。您可以使用OracleConnectionStringBuilder.DataSource属性执行此操作。

在ComboBox的SelectedIndexChanged事件中更新此属性:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
    // A connection string for testing.
    string connectString = "Server=OracleDemo;Integrated Security=True"
    var builder = new OracleConnectionStringBuilder(connectString);
    // Show your connection string before any change.
    Console.WriteLine("ConnString before: {0}", builder.ConnectionString);
    builder.DataSource = comboBox1.SelectedItem.ToString();
    // This will show your conn string has been updated with the user selected database name.
    Console.WriteLine("ConnString  after: {0}", builder.ConnectionString);

    // At this point you're ready to use the updated connection string.
}

您需要使ComboBox使用DropDownStyle.DropDownList值,以便用户无法输入自己的数据库名称。