2013-03-21 34 views

回答

1

與弗萊姆的解決方案非常相似,但更簡單。它使用Select方法的一個過載,其中在當前item旁邊的是它被傳遞的index

ddl.DataSource = arrayOfStrings.Select((text, index) => new { text, index }) 
           .ToList(); 

ddl.DataValueField = "index"; 
ddl.DataTextField = "text"; 
ddl.DataBind(); 
+0

@IIyaIvano我喜歡它,但對我的帖子的評論本來是合適的。 +1。 – 2013-03-21 19:42:14

+0

@flem當我看到你發佈了你的帖子時,我幾乎已經寫完了我的帖子,所以這並不像我完全竊取你的答案。對不起,如果有任何不好的想法出現在你腦海中 – 2013-03-21 19:43:53

0

在這裏,你走了,通知我可是從我的數據集設置數據文本和值字段到特定的列。

SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString); 
     DataSet ds = new DataSet(); 
     SqlCommand cmd = new SqlCommand("Select * from country", cn); 
     SqlDataAdapter adp = new SqlDataAdapter(cmd); 
     adp.Fill(ds); 
     Dropdownlist1.DataSource = ds; 
     Dropdownlist1.DataTextField = "CountryName"; 
     Dropdownlist1.DataValueField = IndexOf("CountryID"); 
     Dropdownlist1.DataBind(); 
3

您需要一個值來綁定而不是計算。做一個強大的班級,或者在下面的例子中用一個快速而簡單的匿名類型做這件事。

List<string> ds = yourlist; 
ddl.DataSource = yourlist 
    .Select(s => new 
    { 
     Text = s, 
     Value = yourlist.IndexOf(s) 
    }) 
    .ToList(); 
ddl.DataValueField = "Value"; 
ddl.DataTextField = "Text"; 
ddl.DataBind(); 
+1

+1 Flemster,歡迎回來;) – mattytommo 2013-03-21 19:40:49

相關問題