I am new to WPF. I am bind data table to data grid in my wpf project. I have button present in my DataGrid and on button click event, I am trying to find the GridViewRow. But I am getting Grdrow1 as null.
My Code:
<my:DataGrid Name="GridView1" ItemsSource="{Binding}" AutoGenerateColumns="False" >
<my:DataGrid.Columns>
<my:DataGridTemplateColumn Header="Vehicle Reg. No." Width="SizeToCells">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Name="btnUserId" Cursor="Hand" Click="btnUserId_Click" Content="{Binding Path=VehicleReg }" Style="{StaticResource LinkButton}"></Button>
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
<my:DataGridTextColumn Header="Vehicle Name" Binding="{Binding Path=VehicleName}">
</my:DataGridTextColumn>
</my:DataGrid.Columns>
</my:DataGrid>
My C# code is:
private void btnUserId_Click(object sender, RoutedEventArgs e)
{
GridViewRow Grdrow1 = ((FrameworkElement)sender).DataContext as GridViewRow;
}
——-My Edited Post——
I have use the below namespace for GridViewRow:-
using System.Web.UI.WebControls;
This is current or any other I have to use?
First off, make sure you’re not confusing DataGrid with a GridView (of a ListView). It seems your Xaml is using DataGrid, but you’re trying to cast to a GridViewRow which is not present in DataGrids. You are probably looking for a DataGridRow instead.
Making this change is not enough however – you’ll still be attempting a cast that won’t succeed. The sender of the Click event in WPF is simply the object that was used to hook up the event handler, which is Button in this case. In order to find the DataGridRow that contains this Button, you’ll have to walk up the WPF Visual Tree until you find it using the VisualTreeHelper class.
Keeping the same Xaml, here is what I propose for the Click event handler. Notice that the sender is the Button. Starting from that, we just climb the Visual Tree by using the VisualTree.GetParent method until we find the first object that is of type DataGridRow.