0

On my program I have 2 forms. First one is to save information to xml file from textboxes and the second for is to search xml elements based on text that I write in textbox and show them in listview.

The problem is that when I get the results, in listview everything looks fine, but when I click the item in listview I get all information for xml element with index 0.

This is the code I use to search the xml and the code for SelectedindexChanged:

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);


            XmlDocument cDoc = new XmlDocument();

            cDoc.Load(path + "\\MyProgram\\Data.xml");
            var doc = XDocument.Load(path + "\\MyProgram\\Data.xml");


            var q = from el in doc.Root.Elements("Register")
                    let str = el.Element("Name").Value
                    where str.ToLower().Equals(textBox1.Text)
                    select new ListViewItem(el.Elements().Select(x => x.Value).ToArray());


            listView1.Items.AddRange(q.ToArray());

and for selectedIndexChange

 name.Text = History[listView1.SelectedItems[0].Index].Name;
 lastname.Text = History[listView1.SelectedItems[0].Index].Lastname;

Please help me because it's begin a week that I'm searching for a solution.

  • 'q' is an array (ToArray()) so why are you doing AddRange(q.ToArray)? If q is a string you are adding characters to the listView1. – jdweng Apr 15 '16 at 09:08
  • There is no problem with listview. The only problem is that SelectedIndexChange is taking index number from XML file. For example after searching a name I have a result on Listview in the first row, the name in the XML is in index 5, but the first Row in listview has index 0, so when i click on it I have all information for index 0 on XML fil and this is wrong. – TheBond Apr 15 '16 at 10:05

1 Answers1

0

Try using the SelectedIndex property of your ListView instead of SelectedItems[0].Index.

Update: With WinForms see this question Why isn't 'SelectedIndex' defined on this ListView?:

listView1.SelectedIndices[0]
Community
  • 1
  • 1
Timothée Bourguignon
  • 2,190
  • 3
  • 23
  • 39