5

How to read a cell value form a WPF DataGrid?

I search online and try any possible combination and nothing works:

Datagrid.Cells[..], DataGrid.Items.Cells[..], DataGrid.Rows.., DataGrid.Items.Row.. nothing works, I can't find it is MSDN or I don't understand it. I just need to read a value off a cell in DataGrid that simple.

How to do it?

KMC
  • 19,548
  • 58
  • 164
  • 253

5 Answers5

4

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();
}
icernos
  • 395
  • 3
  • 6
3

This might help someone else.

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

Good luck!

BlackCath
  • 816
  • 13
  • 23
3

Check this

http://social.msdn.microsoft.com/Forums/en/wpf/thread/74332b78-6bfd-4ac9-af85-dfd9bec87a29

http://wpfadventures.wordpress.com/2008/12/02/wpf-datagrid-detecting-clicked-cell-and-row/

WPF Toolkit DataGrid SelectionChanged Getting Cell Value

Community
  • 1
  • 1
biju
  • 17,554
  • 10
  • 59
  • 95
  • from your answer it seems I have to write a helper function to get one cell value out of a DataGrid. I have hundreds of rows and multiple columns in my DataGrid. To get all values I have to loop through all rows and run the helper functions hundreds of time. Is there a quicker way? – KMC Apr 05 '11 at 09:32
  • 1
    @KMC It depends on what you are trying to do.Why do you want to loop through all the cells and get the data in cells ? You can simply use databinding to your code behind or viewmodel and loop your collection instead. – biju Apr 05 '11 at 09:41
  • I have to select a good number of cells in a DataGrid and output to an Excel sheet. That's why I'm looking for a more intuitive way to do that. I will reword my question and post a new question. – KMC Apr 05 '11 at 09:46
  • 2
    @biju - Please edit this answer so it can be understood without following the links so we are safe from link-rot. – Emond Oct 11 '15 at 19:11
  • @KMC No helpers should be needed. Learn XAML, use data binding. Doing this stuff in c# with XAML is always a mess -- you're fighting against the framework. He's helping you do it the wrong way, but it's still the wrong way. – 15ee8f99-57ff-4f92-890c-b56153 Apr 13 '16 at 00:15
1

for wpf use:

DataRowView item = dataGrid.Items[rowIndex] as DataRowView;
Console.WriteLine(item.Row.ItemArray[columIndex]);
Pixel_95
  • 954
  • 2
  • 9
  • 21
0

The following helped me:

Private Sub dgNames_MouseDoubleClick(sender As Object, e As MouseButtonEventArgs) Handles dgNames.MouseDoubleClick

    Dim strCellContent as String = MessageBox.Show(TryCast(e.OriginalSource, TextBlock).Text)

End Sub
Dwargh
  • 9
  • 1