A new home

I’ve made the move to WordPress!

You should be automatically redirected in 5 seconds. Please visit World Wide Code on Wordpress

Hope to see you there!
Showing posts with label data grid. Show all posts
Showing posts with label data grid. Show all posts

Saturday, February 26, 2011

Accessing data grid row from an event


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.