0

branch is of checkbox list type, but while looping through this it adds only one item while i want to store all "li" in branch_id and want to retrive later why it's not adding all in branch_is. is there any other option which can add all this to variable branch_id.

          foreach (ListItem li in branch.Items) 
                {
                    if(li.Selected)
                    {

                        List<int> branch_id = new List<int>();
                        branch_id.Add(Convert.ToInt32(li.Value));

                    }
                } 

3 Answers 3

1

Try this one

List<int> branch_id = new List<int>();
foreach (ListItem li in branch.Items) 
{
     if(li.Selected)
     {
          branch_id.Add(Convert.ToInt32(li.Value));
     }
} 

Or this one if you are using .Net 3.5 or higher and can use LINQ

List<int> branch_id = branch.Items.Where(li=>li.Selected).Select(li=>li.Value).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

oh my god every time a new object was creating that's y
0

you no need for initializing the List<int> branch_id = new List<int>(); again.

If you initialize it will create a new instance for the branch_id and clear all the present value.

foreach (ListItem li in branch.Items) 
                {
                    if(li.Selected)
                    {

                        List<int> branch_id = new List<int>(); // during each time it loops it create new memory and you can't save all the values
                        branch_id.Add(Convert.ToInt32(li.Value));

                    }
                }



so do 

List<int> branch_id = new List<int>(); 
foreach (ListItem li in branch.Items) 
                {
                    if(li.Selected)
                    {


                        branch_id.Add(Convert.ToInt32(li.Value));

                    }
                } 

Comments

0

I once wrote about an extension method that allows me to simplify the selection with LINQ:

var branch_id = branch.Items.WhereSelected().Select(i => Convert.ToInt32(i.Value)).ToList()

1 Comment

i am using 2.o thats y it doesn't work in that i think. Well yours answer is of a great help as well. thanks

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.