Accessing of Rows in Silverlight DataGrid

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

Imagine you want to enumerate (enlist) all rows (DataGridRow) of Silverlight Grid (DataGrid). By design this is not very simple tasks.
For example, you want to do something like this:

            foreach (DataGridRow rowItem in grid.Rows)
            {
                   . . .
             }

This very important and very frequent requirement is just an issue. You will notice that this is almost impossible and will start to research in internet. Good luck. So, I decided to post the code of extension class which makes this possible:

            foreach (DataGridRow rowItem in grid.GetRows())
            {
                   . . .
             }

Here is the whole code:

    /// <summary>
    /// Extends the DataGrid.
    /// </summary>
    public static class DataGridExtensions
    {
        /// <summary>
        /// Gets the list of DataGridRow objects.
        /// </summary>
        /// <param name="grid">The grid wirhrows.</param>
        /// <returns>List of rows of the grid.</returns>
        public static ICollection<DataGridRow> GetRows(this DataGrid grid)
        {
            List<DataGridRow> rows = new List<DataGridRow>();

            foreach (var rowItem in grid.ItemsSource)
            {
                // Ensures that all rows are loaded.
                grid.ScrollIntoView(rowItem, grid.Columns.Last());

                // Get the content of the cell.
                FrameworkElement el = grid.Columns.Last().GetCellContent(rowItem);

                // Retrieve the row which is parent of given element.
                DataGridRow row = DataGridRow.GetRowContainingElement(el.Parent as FrameworkElement);

                // Sometimes some rows for some reason can be null.
                if (row != null)
                    rows.Add(row);
            }

            return rows;
        }
    }

The code above shows theoretically the idea of accessing of rows. Unfortunately this will work only if the whole grid result can be placed at the current view. While calling of ScrollIntoView() grid will reuse instances of created cells and rows and replace with new bounded data over and over again. The result of so called row virtualization will be replacing of rows in the list.
To workaround this, I implemented the right extension method

public static IEnumerator<DataGridRow> GetRowsEnumerator(this DataGrid grid)
{
   
return new GridRowEnumerator(grid);
}


And here is the implementation of enumerator:

  public class GridRowEnumerator : IEnumerator<DataGridRow>
    {
        private DataGrid m_Grid;

        private IEnumerator m_Enumerator;

        public GridRowEnumerator(DataGrid grid)
        {
            m_Grid = grid;

            m_Enumerator = m_Grid.ItemsSource.GetEnumerator();
        }

        #region IEnumerator<DataGridRow> Members

        public DataGridRow Current
        {
            get
            {
                var rowItem = m_Enumerator.Current;

                // Ensures that all rows are loaded.
                m_Grid.ScrollIntoView(rowItem, m_Grid.Columns.Last());

                // Get the content of the cell.
                FrameworkElement el = m_Grid.Columns.Last().GetCellContent(rowItem);

                // Retrieve the row which is parent of given element.
                //DataGridRow row = DataGridRow.GetRowContainingElement(el);
                DataGridRow row = DataGridRow.GetRowContainingElement(el.Parent as FrameworkElement);

                return row;
            }
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
           
        }

        #endregion

        #region IEnumerator Members

        object IEnumerator.Current
        {
            get
            {
                return this.Current;
            }
        }

        public bool MoveNext()
        {
            return m_Enumerator.MoveNext();
        }

        public void Reset()
        {
            m_Enumerator.Reset();
        }

        #endregion
    }






This line I put here to measure how some interesting words can dramatically increase landing frequency of boring technical posts.

Bayern Inter Football Soccer champions league  

Please forgive me for this :)


Posted May 02 2010, 12:30 AM by Damir Dobric
Filed under:

Comments

Joseph DeCarlo wrote re: Accessing of Rows in Silverlight DataGrid
on 08-27-2010 20:39

Works great!  Thanks for the good post.

Tom Graham wrote re: Accessing of Rows in Silverlight DataGrid
on 09-23-2010 16:50

Do you have a sample application?  How do I apply the extension to the datagrid?  Can I tell whether or not the row is selected?

Silverlight wrote re: Accessing of Rows in Silverlight DataGrid
on 11-12-2010 15:35

Can you paste ful source code here with sample

Yurii wrote re: Accessing of Rows in Silverlight DataGrid
on 12-20-2010 10:17

Thanks a lot!!! )) really helpfull how to find DataGridRow

beauXjames wrote re: Accessing of Rows in Silverlight DataGrid
on 12-23-2010 20:53

I do appreciate the post here...the use case was to cross apply a series of different SolidColorBrushes to various rows in a single grid based on a certain key value in one of the columns. The cool little extension I applied to extend this concept was assigning a type to the rowItem, which was then open all too easily to the code for running logic on a row-by-row basis...and, of course, when streamingly fast.

Sunil Gohel wrote re: Accessing of Rows in Silverlight DataGrid
on 01-21-2011 12:53

I think there is no any Last() method in IEnumerator interface..

I have taken the code but it gives me an error that Last() could not found.

Can u elobrate this.

Damir Dobric Posts wrote How to register Button ClickHandler of button in DataGrid in TemplateControl
on 02-03-2011 11:08

Registering of Click event of a button contained in the datatemplate of datagrid which is contained in

DamirDobric wrote How to register Button ClickHandler of button in DataGrid in TemplateControl
on 02-03-2011 12:05

Registering of Click event of a button contained in the datatemplate of datagrid which is contained in

Damir Dobric Posts wrote How to register Button ClickHandler of button in DataGrid in TemplateControl
on 02-03-2011 23:58

Registering of Click event of a button contained in the datatemplate of datagrid which is contained in

fjg wrote re: Accessing of Rows in Silverlight DataGrid
on 03-11-2011 1:36

Just I need

Mohak Mahato wrote re: Accessing of Rows in Silverlight DataGrid
on 05-20-2011 11:46

COOL

Raman wrote re: Accessing of Rows in Silverlight DataGrid
on 08-05-2011 1:45

Can we expect a complete code for this sample? It will be very helpfull.

tw wrote re: Accessing of Rows in Silverlight DataGrid
on 08-12-2011 18:12

About grid.Columns.Last() error,

It dose not contain definittion for "Last()"

tomW wrote re: Accessing of Rows in Silverlight DataGrid
on 08-16-2011 18:30

Columns.Last())

Columns dose not have Last() mothed?

vova wrote re: Accessing of Rows in Silverlight DataGrid
on 11-18-2011 12:37

if you use ScrollViewer, it could be simpler

dataGrid.UpdateLayout();

Pager.PageSize = 50; //just as many as cause scroll bar to be visible

dataGrid.UpdateLayout();

Pager.PageSize = (int)((ScrollViewer.ActualHeight / row.ActualHeight) - 1);

Salvador wrote re: Accessing of Rows in Silverlight DataGrid
on 11-24-2011 1:11

I got an error on the following line

               private IEnumerator m_Enumerator;

 "IEnumerator" requires one type argument

beauXjames:

do you have thesample wher you aplied the code?

ali wrote re: Accessing of Rows in Silverlight DataGrid
on 03-13-2012 12:40

using System.Windows.Controls.Primitives

var rowsPeresentor = myGrid.GetVisualDescendants().OfType<DataGridRowsPresenter>().FirstOrDefault();

var Rows = rowsPeresentor.GetVisualDescendants().OfType<DataGridRow>();

foreach (var row in Rows)

{

if (row.GetIndex() == myGrid.SelectedIndex)

{

//your code

break;

}

}

kc wrote re: Accessing of Rows in Silverlight DataGrid
on 04-27-2012 20:07

To get m_Grid.Columns.Last() to work add using System.Linq; to the usings

Marco wrote re: Accessing of Rows in Silverlight DataGrid
on 06-15-2012 21:27

Very good! Thank you very much!

developers.de is a .Net Community Blog powered by daenet GmbH.