none
WPF DataGrid Current Row Index and Column Index

    Question

  • I am using DataTable to bind data to WPF DataGrid. How to get current row index and column index of the DataGrid.

    Thanks,
    Sandeep

    Tuesday, December 22, 2009 4:57 AM

Answers

  • int index = this.datagrid.SelectedCells[0].Column.DisplayIndex;
    • Marked as answer by skotrik Wednesday, December 30, 2009 4:02 AM
    Wednesday, December 30, 2009 4:02 AM

All replies

  • Hello Sandeep,

      I am not sure I caught the problem. If there is any misunderstanding, please let me know. Thanks.

      Do the property of SelectedCells and SelectedIndex at DataGrid work for you?

      You can also ask at http://wpf.codeplex.com/Thread/List.aspx due to it is a pre-release Control.

      Thanks.
    Wednesday, December 23, 2009 8:30 AM
  • Yes, SelectedIndex works for me, it gives row index. But I am not sure how to get the column index of the SelectedCell.

    Thanks,
    Sandeep
    Wednesday, December 23, 2009 9:42 AM
  • int index = this.datagrid.SelectedCells[0].Column.DisplayIndex;
    • Marked as answer by skotrik Wednesday, December 30, 2009 4:02 AM
    Wednesday, December 30, 2009 4:02 AM
  • private void DataGrid1_MouseClick(object sender, MouseButtonEventArgs e)
            {
                DependencyObject dep = (DependencyObject)e.OriginalSource;

                //Stepping through the visual tree
                while ((dep != null) && !(dep is System.Windows.Controls.DataGridCell))
                {
                    dep = VisualTreeHelper.GetParent(dep);
                }

                //Is the dep a cell or outside the bounds of Window1?
                if (dep == null | !(dep is System.Windows.Controls.DataGridCell))
                {
                    return;
                }
                else
                {
                    System.Windows.Controls.DataGridCell cell = new System.Windows.Controls.DataGridCell();
                    cell = (System.Windows.Controls.DataGridCell)dep;
                    while ((dep != null) && !(dep is DataGridRow))
                    {
                        dep = VisualTreeHelper.GetParent(dep);
                    }

                    if (dep == null)
                    {
                        return;
                    }
                    int colindex = cell.Column.DisplayIndex;  //this returns COLUMN INDEX
                   
                    DataGridRow row = dep as DataGridRow;
                    System.Windows.Controls.DataGrid dataGrid = ItemsControl.ItemsControlFromItemContainer(row) as System.Windows.Controls.DataGrid;
                    int rowindex = dataGrid.ItemContainerGenerator.IndexFromContainer(row); //this returns ROW INDEX
                    object value = ExtractBoundValue(row, cell);
                    TextBox1.Text = value.ToString(); //this returns cell value
                }
            }
    Vamshi Vemula
    Thursday, March 03, 2011 7:20 PM