Abhi
Abhi

Reputation: 5543

how to get selected column name or index in WPF Grid

Can you please tell how to get selected column name or index in WPF Grid.

Upvotes: 2

Views: 5477

Answers (3)

Abhi
Abhi

Reputation: 5543

This is how we can get the value of a specific cell

Object obj = GetCell(3).Content;
                     string cellContent = String.Empty;
                     if (obj != null)
                     {
                         if (obj is TextBox)
                             cellContent = ((TextBox)(obj)).Text;
                         else
                             cellContent = ((TextBlock)(obj)).Text;
                      }




private DataGridCell GetCell(int column)
    {
        DataGridRow rowContainer = GetRow();

        if (rowContainer != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

            // Try to get the cell but it may possibly be virtualized.
            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            if (cell == null)
            {
                // Now try to bring into view and retreive the cell.
                customDataGrid.UCdataGridView.ScrollIntoView(rowContainer, customDataGrid.UCdataGridView.Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }

Upvotes: 0

HCL
HCL

Reputation: 36815

For the DataGrid, the column you can get via the CurrentCell-property:

DataGridCellInfo cellInfo = dataGrid.CurrentCell;
DataGridColumn column=cellInfo.Column;

Upvotes: 6

p.campbell
p.campbell

Reputation: 100657

Try this to get a list of rows selected:

IList rows = dg.SelectedItems;

From this related question.

Upvotes: 0

Related Questions