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 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());
}
}
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:
You’ll want to make your ComboBox use the DropDownStyle.DropDownList value so users can’t type in their own database names.