开发者

Check List - Get Selected Values into set of Labels (Text)

开发者 https://www.devze.com 2023-03-07 02:33 出处:网络
I will disable the CheckBoxList once a user selects 5 values. I want to take the 5 selected items out of the CheckBoxList and assign them to 5 different labels.

I will disable the CheckBoxList once a user selects 5 values.

I want to take the 5 selected items out of the CheckBoxList and assign them to 5 different labels.

So far I have this:

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

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

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

All that does is get the first character and assign the same value to both labels. How would I iterate through and take e开发者_如何学Cach selected value and assign them to the each label?


    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;


Here's a generic code, suitable for 5 or 50 items/labels:

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

Update

Since you stated you don't have LINQ, you can go like this:

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

Update 2

Keep in mind that both solutions assume that your labels start at Label0. Adjust accordingly. Also, code was adjusted to check if the Label was found.

0

精彩评论

暂无评论...
验证码 换一张
取 消