0

I have foreach loop to listView control, I want to create objects for every listView content, so i want to change the name of the object incrementally by foreach loop

foreach (var item in listViewStates.Items)
            {
               State s = new State 
               {
                   ID = MaxStateID,
                   Name = listViewStates.Items[0].Text,
                   WorkflowID = MaxWFID,
                   DueDate = Convert.ToInt32(listViewStates.SelectedItems[0].SubItems[1].Text),
                   Priority = Convert.ToInt32(listViewStates.SelectedItems[0].SubItems[2].Text),
                   RoleID = Convert.ToInt32(listViewStates.SelectedItems[0].SubItems[3].Text),
                   Status =Convert.ToInt32(listViewStates.SelectedItems[0].SubItems[4].Text)
               };
               i++;
            }

the variable is s from the State Class

1
  • 2
    Where is i defined and where is it used? Commented Jul 29, 2013 at 14:18

1 Answer 1

2

You might have the wrong approach. What you need to do with your state object is add it to a collection, and work it from there. It's much easier to track this way.

Example with a local list for use after the loop, in the function:

public void MyFunction()
{
    List<State> states = new List<State>();

    foreach (var item in listViewStates.Items)
    {
        State s = new State
        {
            //Set state properties
        };
        states.Add(s);
    }
    //Use your states here, address with brackets
    //states[0].ID ...
}

Example with a class-level list for later use outside the function:

List<State> _states;

public void MyFunction()
{
    _states = new List<State>();
    foreach (var item in listViewStates.Items)
    {
        State s = new State
        {
            //Set state properties
        };
        _states.Add(s);
    }
    //Now, after calling the function, your states remain
    //You can address them the same way as above, with brackets
    //_states[0].ID ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

As you see, I declared S from State, but I want to use i variable in naming the object from State to use the objects later....
That can't be done. Put it in a collection to use it later. I'll give you an example.

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.