Reputation: 4993
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?
Upvotes: 3
Views: 2725
Reputation: 675
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);
}
Upvotes: 3
Reputation: 1228
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.
Upvotes: 1