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.

private void Button_Click(object sender, RoutedEventArgs e)
{

//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;

}

It is not necessary to use the GetRowContainingElement method in a click event any event that you have subscribed will do the task.

Advertisements

Share your thoughts

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s