[英]how to set combobox display member and value member by split string
我有列表,其中存儲數據庫名稱和連接字符串,以逗號分隔。 我想將數據庫名稱設置為顯示成員,並將連接字符串設置為組合框的值成員。
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";
}
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" ;
試試這個代碼
您可以將ComboBox綁定到Dictionary:
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";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.