3

I have a dynamically created CheckBoxList. Within this CheckBoxList, I have a nested foreach loop used to validate a user input. The user enters his or her email address. Once the user clicks submit, the CheckBoxList is created. If the user's email matches a subscription to a topic, the checkbox next to that topic is selected. The problem I'm having is relating the original outer foreach to the nested foreach.

int i = 0;
foreach (Topic topic in result)
{
    string topicName = topic.TopicArn.ToString().Split(':').Last();
    ListItem li = new ListItem(topicName, topic.TopicArn);
    checkBoxList1.Items.Add(li);

    foreach (Subscription subscription in subs) // where topic equals current 
                                                // topic in original foreach?
    {
        if (txtEmail.Text == subscription.Endpoint)
            checkBoxList1.Items[i].Selected = true;
    }
    i++;
}

I was thinking I might be able to use LINQ to add a condition to the nested foreach loop, but I haven't been able to pull it all together yet.

0

1 Answer 1

1

You must first create all the checkboxes before you can start evaluating if they should be checked or not. In the code above you create one Listitem then you loop thru all the subscribtions so it will go out of bound in that loop before you create the second listitem in the checkboxlist.

 foreach (Topic topic in result)
 {
   string topicName = topic.TopicArn.ToString().Split(':').Last();
   ListItem li = new ListItem(topicName, topic.TopicArn);
   li.Selected = subs.Any(s => s.Endpoint == txtEmail.Text && s.TopicArn == topic.TopicArn);
   checkBoxList1.Items.Add(li); 
 }
Sign up to request clarification or add additional context in comments.

3 Comments

I appreciate the response, because normally you would be exactly right! I need to be more clear. Each topic can have multiple subscribers. For each of the topics I need to check if the user's email matches any of the subscribers. Then I need to increase the counter and iterate to the next topic. The above throws an ArgumentOutOfRangeException because there are 4 subscriptions and 3 topics (CheckBoxList items). This is a very good start though, so thank you for the help.
Ok, now I have modified my answer to solve your problem with one foreach loop with a linq expresseion that checks for a match beetween Endpoint and txtEmail and if it finds a match returns true.
Perfect! I modified your answer slightly to make sure the topic and subscription we were testing for were related. Can't thank you enough!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.