views:

65

answers:

3

User chose a folder of files. I'm making a listview of files in these folder. I want to display what each file contains,but i want to display it when user check a file from listviewitem. I'm using these code:

if (listView1.Items[0].Checked == true)
{
   //....
}

Why it doesn't work? What should i want to use data from for example:

button1.Click(...) to button2.Click(...)?

+1  A: 

Not sure exactly what you're looking for but there are a number ways to determine which items in a ListView are checked:

// This loops through only the checked items in the ListView.
foreach (ListViewItem checkedItem in listView1.CheckedItems) {
    // All these ListViewItems are checked, do something...
}

// This loops through all the items in the ListView and tests if each is checked.
foreach (ListViewItem item in listView1.Items) {
    if (item.Checked) {
        // This ListViewItem is Checked, do something...
    }
}

You can use the ListViewItem Class to examine the details of each selected item.

Jay Riggs
A: 

I would create a nice MVVM design. The ViewModel would have an ObservableCollection FileList, where File would hold whatever information you want. This class would have also an IsFileSelectedUI property so that you could right in your code. Then in XAML things are easy:

<ScrollViewer Grid.Column="0" Grid.Row="1" >
<ItemsControl ItemsSource="{Binding FileList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Gray" BorderThickness="1" Margin="2" Padding="2">
                <StackPanel Orientation="Horizontal">
                    <CheckBox IsChecked="{Binding IsFileSelectedUI , Mode=TwoWay}"/>
                    <TextBlock Text="{Binding FileName}"/>
                </StackPanel>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Then things are just as easy as:

FileList.Where(file=>file.IsFileSelectedUI) etc

If I understood what you said :)

Aggelos Mpimpoudis
That's not a bad WPF design, but it doesn't answer the OP's question, which was how you determine if an item in a .NET Framework ListView is checked...
djacobson
A: 

Which event are you capturing? Remember if it's the ItemCheck, that you cannot use the listView1.Item[0].Checked if that item was what was checked/unchecked. You need to take the ItemCheckEventArgs parameter, and using the e.Index, exclude that element when checking the entire listview elements. Use e.NewValue to separately evaluate the item that raised the ItemCheck event.

code4life