3

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?

2
  • Are you using MVVM? Commented Sep 4, 2018 at 11:42
  • no. code behind method. Commented Sep 4, 2018 at 11:43

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

In XAML:

<datagrid name="datagrid1" ... mousedoubleclick="datagrid1_MouseDoubleClick"></datagrid>

And use this code:

private void datagrid1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DataGrid dg = sender as DataGrid;

   if (dg!= null && dg.SelectedItems != null && dg.SelectedItems.Count == 1)
   {
       DataRowView dr = dg.SelectedItem as DataRowView;
       int id = Convert.ToInt32(dr["Id"].ToString());
   }
}

I hope it helps you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.