4

I have DataGridRow of a DataGrid, how can I get the individual column values from it? See the code below.

var itemsSource = MESearchDatagrid.ItemsSource as IEnumerable;
if (itemsSource != null)
{
    foreach (var item in itemsSource)
    {
        var row = MESearchDatagrid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (row != null)
        {
        //How to get the Cell value?
        }

    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88

2 Answers2

2

You can cast your row.item to your initial class type.

        var itemsSource = MESearchDatagrid.ItemsSource;
        if (itemsSource != null)
        {
            foreach (var item in itemsSource)
            {
                var row = MESearchDatagrid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                if (row != null)
                {
                    var data = row.Item as UserClass;
                    MessageBox.Show(data.Name);
                }

            }
        }
Mohammad Karimi
  • 387
  • 2
  • 8
2

There is no reason to call the ContainerFromItem method here. The ItemsSource contains the actual data objects. You only need to cast them to your type (called YourClass in the following sample code):

var itemsSource = MESearchDatagrid.ItemsSource as IEnumerable;
if (itemsSource != null)
{
    foreach (var item in itemsSource.OfType<YourClass>())
    {
        var prop = item.Property1;
        //...
    }
}

Property1 is a property of YourClass.

mm8
  • 163,881
  • 10
  • 57
  • 88