Click here to Skip to main content
15,886,077 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi Experts
I want to get values of each cell for every row in dataGrid in WPF On a button click event .Button is Outside of the DataGrid
plz help

Thanks
Posted
Updated 26-Jul-16 14:16pm
v2
Comments
Richard MacCutchan 11-Jul-13 5:44am    
Assuming you mean a DataGridView object then you just need to add some code in your button click handler. If that is not the case then please edit your question and explain your problem in more detail.
ErBhati 11-Jul-13 6:19am    
Its Not a DataGridView Of Windows Form. Its a DataGrid Of WPF(Windows Presentation Foundation).

Use this in youer event handler

C#
var rows = GetDataGridRows(datagrid1);

foreach (DataGridRow r in rows)
{
 //   DataRowView rv = (DataRowView)r.Item;
  foreach (DataGridColumn column in datagrid1.Columns)
  {
      if (column.GetCellContent(r) is TextBlock)
      {
           TextBlock cellContent = column.GetCellContent(r) as TextBlock;
           MessageBox.Show(cellContent.Text);
      }
  }
}

Method to get the rows from datagrid
C#
 public IEnumerable<datagridrow> GetDataGridRows(DataGrid grid)
     {
        var itemsSource = grid.ItemsSource as IEnumerable;
        if (null == itemsSource) yield return null;
        foreach (var item in itemsSource)
        {
          var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                    if (null != row) yield return row;
        }
     }
  
</datagridrow>
 
Share this answer
 
Comments
ErBhati 11-Jul-13 7:01am    
public IEnumerable<datagridrow> GetDataGridRows(DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;

i have some errors in as IEnumerable; and public IEnumerable<datagridrow> line
Naz_Firdouse 11-Jul-13 7:06am    
include namespaces
using System.Collections;
using System.Collections.Generic;
ErBhati 11-Jul-13 7:39am    
Thanks
ErBhati 11-Jul-13 7:44am    
Little more help sir ,How i Bind cellContent value to the datatable every time
ErBhati 12-Jul-13 2:58am    
Thanks sir It give me good Idea..Thanks alot
It is a software bug so :

change column visibility to visible.
remove DataGridTemplateColumn.
it will work good.
 
Share this answer
 
Comments
Member 11514370 11-May-18 5:01am    
Test TargetIndex for -1.
If you move the mouse outside the DataGrid, targetIndex will be negative.
Only exchange when targetIndex is valid (>=0)

also change line "var list = (sender as DataGrid).ItemsSource as ...."
to
"var list = (sender as DataGrid).ItemsSource as IList" when the ItemsSource is an ObservableCollection ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900