开发者

how to connect to a database on select of any value from combobox

I have a combobox which is populated with various database name. I want to connect to a certain database on select of any database name from the combobox. Gow should I go about with this? The code for that is as follows..

private void Form1_Load(object sender, EventArgs e)   
      {  XmlDocument do开发者_JAVA百科c = 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());      
 }   

    } 

I have another code with connection string information

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

So now how should I go about writing a code which on select of any database name from combobox connect me to that specific database. I am new to c# please suggest me a solution. Where should I be including the code?


Well, you can wire up your ComboBox's SelectedIndexChanged event and when it fires you can retreive the selected database from the ComboBox's SelectedItem property and use that in your connection string to connect to your database.

Example
You said you already have a working connection string. All you should need to do is allow your users to change the DataSource portion of that string. You can use the OracleConnectionStringBuilder.DataSource property to do this.

Update this property in your ComboBox's SelectedIndexChanged event:

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.
}

You'll want to make your ComboBox use the DropDownStyle.DropDownList value so users can't type in their own database names.


You could do

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

For Oracle do

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

Hope this help

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜