Search code examples
c#wpfwpfdatagrid

datagrid mouse double click event wpf


I have created an application using WPF. I have shown some data in the data grid. Currently, I have used selection changed event for getting the data from the data grid. I have following code

private void datagrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataGrid dg = sender as DataGrid;
            DataRowView dr = dg.SelectedItem as DataRowView;
            if (dr != null)
            {
                int id = Convert.ToInt32(dr["Id"].ToString());
           }
}

I need to get data only when the user doubles click on the data grid. how is it possible?


Solution

  • XAML:

    <DataGrid MouseDown="datagrid1_MouseDown"></DataGrid>
    

    Code behind:

    private void datagrid1_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.ChangedButton == MouseButton.Left && e.ClickCount == 2)
        {
            DataGrid dg = sender as DataGrid;
            DataRowView dr = dg.SelectedItem as DataRowView;
            if (dr != null)
            {
                int id = Convert.ToInt32(dr["Id"].ToString());
            }
        }
    }
    

    P.S. You can use null propagation to make your code more robust:

    var idStr = ((sender as DataGrid)?.SelectedItem as DataRowView)?["Id"]?.ToString();
    if (idStr != null)
    {
        int id = Convert.ToInt32(idStr);
    }