我有List,用于存储以逗号分隔的数据库名称和连接字符串。我想将数据库名称设置为显示成员,将连接字符串设置为值成员到组合框。
Private void BindDataCombobox(){
List<string> conString =new List<string>();
conString.Add("Database1,'server=server1'");
conString.Add("Database2,'server=server2'");
conString.Add("Database3,'server=server3'");
conString.Add("Database4,'server=server4'");
combobox1.Datasource=conString;
combobox1.DisplayMember="I want to set this to hold Database1,Database2,...etc values";
combobox1.ValueMember="I want this to hold server1,server2,server3....etc";
}
答案 0 :(得分:1)
DataTable dt = new DataTable();
dt.Columns.Add("db",typeof(string));
dt.Columns.Add("server",typeof(string));
foreach(string s in constring)
{
DataRow dr = dt.NewRow();
dr["db"]=s.Split(',')[0];
dr["server"]=s.Split(',')[1].Split('=')[1].Replace("'",string.Empty);
dt.Rows.Add(dr);
}
combobox1.DataSource=dt;
combobox1.DisplayMember="db"; combobox1.ValueMember="server" ;
试试此代码
答案 1 :(得分:0)
您可以将ComboBox绑定到词典:
List<string> conString = new List<string>();
conString.Add("Database1,'server=server1'");
conString.Add("Database2,'server=server2'");
conString.Add("Database3,'server=server3'");
conString.Add("Database4,'server=server4'");
var comboDataSource = conString.ToDictionary(c => c.Split(',')[0], c => c.Split(',')[1]);
comboBox2.DataSource = new BindingSource(comboDataSource, null);
comboBox2.DisplayMember = "Key";
comboBox2.ValueMember = "Value";