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
Published Saturday, November 15, 2008 11:22 AM by preishuber
Filed under: ,

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)