2016-05-15 49 views
0

我有列表存儲數據庫名稱和連接字符串用逗號分隔。我想將數據庫名稱設置爲顯示成員和連接字符串作爲值成員到組合框。如何通過拆分字符串設置組合框的顯示成員和值成員

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

回答

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

試試這個代碼

+0

謝謝你,它是有益的 – Tan

0

您可以在組合框綁定到一個詞典:

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