Click here to Skip to main content
15,881,204 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I added a few rows to my listview. How i can click on one of the row and display the row to textbox.

C#
private void testListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            txtName.Text = testListView.SelectedItems[0].ToString;
        }



This one doesn't work.

Please help.
Posted

1 solution

First I have no strict evidence that your method testListView_SelectionChanged was actually used as a handler added to the invocation list of the event instance of the right instance of the list view. You need to check it up. It is done via the "+=" operator on an event instance. If you ask such questions, you should always show where it is done. (But in WPF, if you use the designer, this code is auto-generated and is not a part of the source code; you can find it under the sub-directory of the project).

So, I always prefer to explicitly add the event handlers with the '+=' operator. (By the way, never use auto-generated names, they violate Microsoft naming conventions and not designed for permanent use; always rename those names to something semantically sensible.)

Also, how do you guarantee that anything is selected at the moment of handling? It would be always good to check up if the element [0] exist, by checking up Count:
http://msdn.microsoft.com/en-us/library/system.collections.icollection.count%28v=vs.110%29.aspx[^] (this is the property of System.Collections.IList implemented by the type of SelectedItems property).

Better yet, use SelectedItem or SelectedIndex:
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selecteditem(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selectedindex(v=vs.110).aspx[^].

In this case, you still need to check up that SelectedIndex is 0 or more or SelectedItem is not null.

As to SelectedItems (plural!) this is only useful if you use multi-select option. Please see:
http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.selecteditems%28v=vs.110%29.aspx[^] (see the comment: "This property is meant to be used when SelectionMode does not equal Single. If the selection mode is Single the correct property to use is SelectedItem."),
http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.selectionmode%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.controls.selectionmode%28v=vs.110%29.aspx[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900