1
votes

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.

3

3 Answers

2
votes

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.

2
votes

This might help someone else.

foreach (DataRowView row in dgLista.SelectedItems)
{
    string text = row.Row.ItemArray[index].ToString();
}

Good luck!

1
votes

Here's a summary of the solution.

Winform

Type: System.windows.Forms.DataGridView

// C#
foreach (DataGridViewRow row in dataGridView1.Rows)
{
  //"Column1" = column name in DataGridView
  string text = row.Cells["Column1"].value.ToString();
}

WPF equivalent

Type: DataGrid

// C#
foreach (DataRowView row in dataGrid.Items)
{
  string text = row.Row.ItemArray[index].ToString();
}