Error executing code with ListView, SelectedItems

2

I have an application which consumes several web services.

What I'm trying to do is once this service is called, which should give me a list of project names, I'd like to add them to a ListView and that the user can choose which project to use.

When I run my code, I get the following error:

Additional information: InvalidArgument=Value of '0' is not valid for 'index'.

Here is my code, could you tell me how I can make it work?

ProjectMetaData[] pr = GetProjectMetaData();

foreach (ProjectMetaData proj in pr)
{   
    var listViewItem = new ListViewItem(proj.ProjectID);
    listView1.Items.Add(listViewItem);

}
projectTitle = this.listView1.SelectedItems[0].Index.ToString();

the projectTitle variable is a getter outside the main:

string projectTitle { get; set; }

Thank you very much

    
asked by A arancibia 10.10.2016 в 17:21
source

1 answer

2

In principle, your upload code of ListView is correct:

ProjectMetaData[] pr = GetProjectMetaData();

foreach (ProjectMetaData proj in pr)
{   
    var listViewItem = new ListViewItem(proj.ProjectID);
    listView1.Items.Add(listViewItem);
}

Later, if you want to detect when the user selects an item from the list, you should do something like this:

First, in the constructor of the Form subscribe to the event SelectedIndexChanged :

this.listView1.SelectedIndexChanged += ListView1_SelectedIndexChanged;

And create a method like this:

private void ListView1_SelectedIndexChanged(object sender, EventArgs e)
{
    projectTitle = this.listView1.SelectedItems[0].Text;
}
    
answered by 10.10.2016 / 17:42
source