简体   繁体   中英

ListView - Grabbing a column value from the selected item

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();

        }

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM