我有一个组合框,其中填充了各种数据库名称。我想在从组合框中选择任何数据库名称时连接到某个数据库。天哪,我应该这样做吗?其代码如下..
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;
}
那么现在我应该如何编写代码,从组合框中选择任何数据库名称将我连接到该特定数据库。我是 c# 的新手,请给我一个解决方案。我应该在哪里包含代码?
最佳答案
那么,您可以连接 ComboBox 的 SelectedIndexChanged event当它触发时,您可以从 ComboBox 的 SelectedItem property 中检索选定的数据库。并在您的连接字符串中使用它来连接到您的数据库。
例子
你说你已经有了一个有效的连接字符串。您需要做的就是允许您的用户更改该字符串的数据源部分。您可以使用 OracleConnectionStringBuilder.DataSource属性(property)来做到这一点。
在 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 值,这样用户就无法输入他们自己的数据库名称。
关于c# - 如何在从组合框中选择任何值时连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5893158/