When using a Data grid in Silverlight, there comes a situation when you want to get the row(or cell) that contains your text box, hyperlink button or any other control. You try to see if the Data Grid has a property like Rows or something which can give you the handle of the current row. Many people do not know is that the DataGridRow class has a static method GetRowContainingElement which takes the control that you have placed in that row and returns you that row object.
So, consider you have a button in some column of a row, now add an event handler for the click event of the button. The following code describes the way to get the clicked row and its related objects.
So, consider you have a button in some column of a row, now add an event handler for the click event of the button. The following code describes the way to get the clicked row and its related objects.
private void Button_Click(object sender, RoutedEventArgs e)It is not necessary to use the GetRowContainingElement method in a click event any event that you have subscribed will do the task.
{
//Get clicked row}
var dataGridrow = DataGridRow.GetRowContainingElement(sender as FrameworkElement);
//Or get clicked index
var roIndex = DataGridRow.GetRowContainingElement(sender as FrameworkElement).GetIndex();
//Or if you need any column of clicked row
//Suppose column1 contains a TextBox
var textBox = myDataGrid.Columns[1].GetCellContent(dataGridrow) as TextBox;