ListView - Grabbing a column value from the selected item

14,045

Solution 1

Try to cast SelectedItem to specific type. After that you'll be able to access full set of the item's properties. Since you have anonymous type here, try to cast it to dynamic :

var selectedItem = (dynamic)myListView.SelectedItems[0];
MessageBox.Show(selectedItem.Col3);

Solution 2

For me, it worked like this:

myListView.SelectedItems[0].SubItems[1].Text;

However, I fill the listview from sql database. You just create items, but no subitems. Here is the reference, how to create:

https://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.subitems(v=vs.110).aspx

Share:
14,045
user1189352
Author by

user1189352

Updated on June 04, 2022

Comments

  • user1189352
    user1189352 almost 2 years

    I'm trying to avoid databinding as i don't understand it and need to get this finished.. but everything I'm trying doesn't seem to work. For example i'd like to print out the 2nd column of the selected item.. but everything I see on google says to use SubItems when mine doesn't have one for some reason?

    <ListView Name="myListView" MouseDoubleClick="myListView_MouseDoubleClick_1">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="H1" DisplayMemberBinding="{Binding Col1}"/>
                        <GridViewColumn Header="H2" DisplayMemberBinding="{Binding Col2}"/>
                        <GridViewColumn Header="H3" DisplayMemberBinding="{Binding Col3}"/>
                    </GridView>
                </ListView.View>
            </ListView>
    
            private void Button_Click_1(object sender, RoutedEventArgs e)
            {
                myListView.Items.Add(new { Col1 = "test1", Col2 = "Test2", Col3 = "test3" });
            }
    
            private void myListView_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
            {
                //THIS DOESN'T WORK, SubItems doesn't exist?
                myListView.SelectedItems[0].SubItems[0].Text.ToString();
    
            }