get ID inside a Silverlight Datagrid when Button clicked

This blog pots describes a datagrid and a encapsulated custom button for each row. I want to show two methods how to get information about the underlaying data of the row.

I use a ado.net data service and a entity datamodel, which is not part of the article, to get the data. Database is good old northwind and table is customer. When use clicks on button messagebox comes up with some information about the row.

image

First the xaml code

<Grid x:Name="LayoutRoot" Background="White">
<data:DataGrid x:Name="DataGrid1" >
            <data:DataGrid.Columns>
                <data:DataGridTemplateColumn Width="100">
                    <data:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="{Binding CustomerID}" Click="Button_Click" Tag="{Binding CustomerID}"></Button>
                        </DataTemplate>
                    </data:DataGridTemplateColumn.CellTemplate>
                </data:DataGridTemplateColumn>
            </data:DataGrid.Columns>
</data:DataGrid>

The databinding to the tag attribute is necessary for my first trick

Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        MessageBox.Show(CType(e.OriginalSource, Button).Tag)
End Sub

Easy or? Do you like it more complex, than following code gives you the select row as number

Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim datenliste As List(Of ServiceReference1.Customers)
        datenliste = DataGrid1.ItemsSource 'automatischer cast
        Dim datenButton As Object = CType(e.OriginalSource, Button).DataContext()
        MessageBox.Show(datenliste.IndexOf(datenButton))
End Sub

2 Comments

  • Worked great thanks! C# version

    private void Button_Click(System.Object sender, System.Windows.RoutedEventArgs e)
    {

    MessageBox.Show((String)((Button)e.OriginalSource).Tag;)



    }

  • I have to find out the row number when mouse moves on it i.e. using mouse-move event.How can i do this ? Do you have any idea ?

Comments have been disabled for this content.