tags:

views:

33

answers:

1

Hi,

I am trying to find out how to read the value of my WPF datagrid cells.

something along the lines of

String myString = myDataGrid.Cells[1][2].ToString();

the datagrid has been created in XAML and i have populated the datagrid with row data by using

reportGrid.Items.Add(new cbResultRow() { ... });

now I want to go back and read cell values in my datagrid.

I have seen some examples of reading data from a selected row or cell, by I don't have any selection (the user doesnt interact with the datagrid).

i have also seen code like

foreach(DataGridRow myrow in myDataGrid.Rows)

however the compiler says Rows is not a member of datagrid.

I have searched for several hours to try to find out how to do what I would have thought was a very simple thing!

please help,

Thanks, will.

A: 

The WPF datagrid was built to bind to something like a DataTable. The majority of the time, you will modify the DataTable, and the Rows/Columns within the DataTable that is bound to the DataGrid.

The DataGrid itself is the Visual Element for the DataTable. Here is a pretty good tutorial on how to do this. To modify data within a loop would look something like this.

foreach(DataRow row in myTable.Rows)
{
    row["ColumnTitle"] = 1;
}

This would simply make all the values in Column "ColumnTitle" equal to 1. To access a single cell it would look something like this.

myTable.Rows[0][0] = 1;

This would set the first cell in your DataTable to 1.

jsmith
Thanks for the reply, I had already done it similar the way you suggested by first creating a List (since there is no datatable) and binding the datagrid to the list, but I really wanted to know if there is a way to access cell data directly from the datagrid.
dontpanic
@dontpanic there is not. And in the future, you'll find that a List does not work near as well as a DataTable. I would even prefer an ObservableCollection over a List.
jsmith