Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of the clicked button in a listbox

I have a list box having delete button in each row so when i clicked the delete button i need the clicked index of list box so as to delete the row.how can i get the index of the clicked item?

here is my listbox

 <ListBox  HorizontalAlignment="Left" Name="listBox1" Margin="-3,132,0,0" VerticalAlignment="Top" Width="498" SelectionChanged="listBox1_SelectionChanged">

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border BorderThickness="0,1,0,0" BorderBrush="#FFC1BCBC" Width="490">
                        <Grid Height="70">
                            <Image Height="50" 
                           HorizontalAlignment="Left" 
                           Name="image" 
                           Stretch="Fill" 
                           VerticalAlignment="Top" 
                           Width="50" 
                           Source="{Binding iconPath}" Margin="8,8,0,0" />
                            <TextBlock Name="Name" Text="{Binding displayName}" VerticalAlignment="Center" Margin="60,0,0,0" Foreground="Black" FontWeight="SemiBold"></TextBlock>

                            <Button Name="btnDeleteRow" Width="50" Click="btnDeleteDashboard_Click" Margin="390,0,0,0" BorderBrush="Transparent" Style="{StaticResource logoutbtn_style}">

                            </Button>
                        </Grid>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
like image 866
Sujiz Avatar asked Dec 28 '22 14:12

Sujiz


1 Answers

I assume your ListBox is databound to some source collection? If this is the case, the DataContext of your button will be an instance of one of your bound items. You can then do as follows:

// if for example you bind a list of MyDataObject instances ...

// create a list
List<MyDataObject> myDataObjects = CreateTestData();

// bind it
listBox1.ItemSource = myDataObjects;

...

// in your click handler
private void btnDeleteDashboard_Click(object sender, EventArgs args)
{
  // cast the sender to a button
  Button button = sender as Button;

  // find the item that is the datacontext for this button
  MyDataObject dataObject = button.DataContent as MyDataObject;

  // get the index
  int index = myDataObjects.IndexOf(dataObject);
}
like image 193
ColinE Avatar answered Jan 13 '23 13:01

ColinE