Muhammad Abbas Muhammad Abbas - 6 days ago 6
C# Question

How to Get the Index of ListView Row on Button Click

I am making a wpf Application and encountered a Problem.
I have used a listview and added a Button in it via Xaml.

<ListView x:Name="list_View" Grid.Column="2" Margin="0,0,0,53" Grid.Row="1" MouseDoubleClick="list_View_MouseDoubleClick" ItemContainerStyle="{DynamicResource alternatingListViewItemStyle}" AlternationCount="2">
<ListView.Style>
<Style TargetType="{x:Type ListView}">
<Setter Property="BorderBrush" Value="Blue"/>
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="Margin" Value="0"/>
</Style>
</ListView.Style>
<ListView.Resources>
<Style x:Key="alternatingListViewItemStyle" TargetType="{x:Type ListViewItem}">
<!-- setting row height here -->
<Setter Property="Height" Value="30" />
<Setter Property="BorderBrush" Value="Blue"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Background" Value="#E7F8FE"/>

</Style>

</ListView.Resources>

<ListView.View>

<GridView>
<GridViewColumn Header="Product Name" Width="100" DisplayMemberBinding="{Binding Product_Name}"/>
<GridViewColumn Header="Unit Price" Width="70" DisplayMemberBinding="{Binding Unit_Price}"/>
<GridViewColumn Header="Quantity" Width="50" DisplayMemberBinding="{Binding Quantity}"/>
<GridViewColumn Header="Total" Width="60" DisplayMemberBinding="{Binding Total}" />
<GridViewColumn Header="Delete" Width="60">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Button Content="X" Width="30" Click="Delete_Item_In_Cart_Click" Name="btn_Delete_Item_In_Cart">

</Button>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>

</GridView>
</ListView.View>
</ListView>


The Lisview I got looks like this:
ListView Image

I want to get the index of Listview Row on Button Click.
The code behind button click is:

private void Delete_Item_In_Cart_Click(object sender, RoutedEventArgs e)
{
try
{
int index2 = list_View.SelectedIndex;
MessageBox.Show(index2.ToString());

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

}


**Issue: **When I click on Button in any row of listview It always gives me the same index,
What I got as Output is:
this Message Box

Thanks in Advance

Answer

Finally I got my issue resolved. Here is the Solution and Process I followed.

1: First of All I added these lines to my existing Xaml in <ListView.Resourses/>

          <Style TargetType="ListViewItem">
                <Style.Triggers>
                    <Trigger Property="IsKeyboardFocusWithin" Value="True">
                        <Setter Property="IsSelected" Value="True"/>

                    </Trigger>
                </Style.Triggers>
                <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
            </Style>

2: And For the C# Code, I added the SelectCurrentItem Handler Mentioned above in Xaml.

Here is the Code for the Event Handler that did the actual task for me.

    private void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
    {                                                                            
        //By this Code I got my `ListView` row Selected.
        ListViewItem item = (ListViewItem)sender;
        item.IsSelected = true;

    }

3: Now to get the Index of the selected ListView Row was Pretty much easy and simple for me. And the Old Code behind the Button Click worked Perfectly for me.

So Finally Here I am Giving All the Code that is fully tested and error free.

1: Xaml: This is the code for ListView

 <ListView x:Name="list_View" Grid.Column="2" Grid.Row="1" Margin="0,0,0,103">

        <ListView.Style>
            <Style TargetType="{x:Type ListView}">

                <Setter Property="BorderBrush" Value="Blue"/>
                <Setter Property="BorderThickness" Value="2"/>
                <Setter Property="Margin" Value="0"/>
            </Style>
        </ListView.Style>
        <ListView.Resources>
            <Style TargetType="ListViewItem">
                <Style.Triggers>
                    <Trigger Property="IsKeyboardFocusWithin" Value="True">
                        <Setter Property="IsSelected" Value="True"/>

                    </Trigger>
                </Style.Triggers>
                <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
                <Setter Property="Height" Value="30" />
                <Setter Property="BorderBrush" Value="Blue"/>
                <Setter Property="BorderThickness" Value="1"/>
                <Setter Property="Background" Value="#E7F8FE"/>
            </Style>

        </ListView.Resources>

        <ListView.View>

            <GridView>
                <GridViewColumn Header="Product Name"  Width="120"  DisplayMemberBinding="{Binding Product_Name}"/>
                <GridViewColumn Header="Unit Price" Width="70" DisplayMemberBinding="{Binding Unit_Price}"/>
                <GridViewColumn Header="Quantity" Width="50" DisplayMemberBinding="{Binding Quantity}"/>
                <GridViewColumn Header="Total"  Width="60" DisplayMemberBinding="{Binding Total}"  />
                <GridViewColumn Header="Delete"  Width="80">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="X" Width="60" Click="Delete_Item_In_Cart_Click" Name="btn_Delete_Item_In_Cart" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">

                            </Button>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>

            </GridView>
        </ListView.View>

    </ListView>

2: C# Code:

    private void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
    {
        ListViewItem item = (ListViewItem)sender;
        item.IsSelected = true;

    }

private void Delete_Item_In_Cart_Click(object sender, RoutedEventArgs e)
{
    try
    {   
        int index =0;
        index = list_View.SelectedIndex;
        MessageBox.Show(index.ToString());

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }  

} 
Comments