2011-05-20 68 views
4

一旦用戶選擇5個值,我將禁用CheckBoxList。檢查清單 - 將選定的值輸入標籤集(文本)

我想從CheckBoxList中取出5個選定的項目,並將它們分配給5個不同的標籤。

到目前爲止,我有這樣的:

string test = ""; 
string test2 = ""; 

test += CheckBoxList.SelectedValue[0]; 
test2 += CheckBoxList.SelectedValue[1]; 

Label1.Text = test; 
Label2.Text = test2; 

所有這一切確實是得到第一個字符,並分配相同的值到兩個標籤。我將如何遍歷並獲取每個選定的值並將它們分配給每個標籤?

+0

可能重複http://stackoverflow.com/questions/6061045/c-checkbox-list-selected-items-text-to-labels -text) – Stecya 2011-05-20 14:35:24

+0

這不是重複的,因爲OP不想寫出每個項目是否被選中。 OP希望將選定項目的值放入文本框中。 – 2011-05-20 14:53:08

+0

這是WinForms還是ASP.NET? – 2011-05-20 15:32:02

回答

0

這裏有一個通用的代碼,適合5個或50個項目/標籤:

var selected = CheckBoxList.Items.Cast<ListItem>().Where(it => it.Selected) 
for (i=0; i < selected.Count(); i++) 
{ 
    lb = FindControl("Label" + i); 
    if(lb != null) 
     ((Label)lb).Text = selected.ElementAt(i).Value; 
} 

更新

既然你說你沒有LINQ,你可以去這樣的:

int i = 0; 
foreach (var item in CheckBoxList.Items) 
{ 
    if (item.Selected) 
    { 
     lb = FindControl("Label" + i); 
     if(lb != null) 
      ((Label)lb).Text = item.Value; 
     i++; 
    } 
} 

更新2

請記住,這兩種解決方案都假定您的標籤始於Label0。相應地調整。此外,還調整了代碼以檢查是否找到標籤。

+0

我沒有Linq。 – brmcdani44 2011-05-20 15:04:51

+0

然後提供更多的環境信息。 – 2011-05-20 15:09:03

0
var labels = new List<string>(); 
    int count = 0; 
    foreach (ListItem item in CheckBoxList1.Items) 
    { 
     if (item.Selected) 
      labels.Add(item.Value); 
    } 


    string mylabel1 = labels.Count > 0 ? labels[0] : string.Empty; 
    string mylabel2 = labels.Count > 1 ? labels[1] : string.Empty; 
    string mylabel3 = labels.Count > 2 ? labels[2] : string.Empty; 
    string mylabel4 = labels.Count > 3 ? labels[3] : string.Empty; 
    string mylabel5 = labels.Count > 4 ? labels[4] : string.Empty; 
[C#複選框列表選定Items.Text到Labels.Text](的
+0

你應該嘗試識別模式。看看你的最後5行。那裏有一個模式。如果不是5,OP要檢查10嗎? PS:沒有downvote,你的回答沒有錯。 – 2011-05-20 15:25:23

+0

@Adrian:是的,通常情況下,它只是一個快速的答案,對5的一個非常具體的要求。它的工作原理 - 因爲我確信你的解決方案使用FindControl。我會離開任何重構到OP :) – iandayman 2011-05-20 15:38:12