(WPF Datagrid) How to determine the column index of an element

How to return the column index of an element in WPat Datagrid when I click on a cell I use Visual Studio 2010 / VB.Net

+3
source share
4 answers

You can use the code below directly to get the selected column index of the cell.

int index = datagrid.SelectedCells[0].Column.DisplayIndex;
+7
source

Have you tried to use this on a Click event for a column index?

int columnIndex = dataGrid.CurrentColumn.DisplayIndex;

I use this code in MouseDoubleClick Event or PreviewKeyUp and it works fine.

+3
source

DataGridCells Click, Selected, , . GotFocus .

.

    <DataGrid ItemsSource="{Binding Data}">
        <DataGrid.CellStyle>
            <Style TargetType="{x:Type DataGridCell}">
                <EventSetter Event="GotFocus" Handler="CellClick"/>
            </Style>
        </DataGrid.CellStyle>
    </DataGrid>

    void CellClick(object sender, RoutedEventArgs e)
    {
        DataGridCell cell = sender as DataGridCell;
        MessageBox.Show(cell.Column.DisplayIndex.ToString());
    }

DataGridCell.Column.DisplayIndex, , , - , DataGrid.Columns.IndexOf(DataGridCell.Column).

+2

Every body talks about this decision.

Int32 columnIndex = dataGridScannedFiles.SelectedCells[0].Column.DisplayIndex;

and yes, it works, but no one says that we should set the Display index first for each column, maybe for experts it is clear, but for beginners this is an unfamiliar thing

There are two ways to install it: -

1) You can install it in the XAML part.

<DataGridTextColumn Header="Serial No." Width="60"  IsReadOnly="True" Binding="{Binding Path=Sno}" DisplayIndex="1"></DataGridTextColumn>

I don't know how to set it for custom columns e.g.

    <DataGridTemplateColumn.CellTemplate>
                                   <DataTemplate>                                                            
    <CheckBox x:Name="ChkItem" IsChecked="{Binding Path=Sno}"/>                                
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>

so I preferred a different way

2) Created Function

private void SetDisplayIndexforGridViewColumns() 
        {
            Int32 ColumnCount = dt.Columns.Count;

            for (int i = 0; i < ColumnCount; i++) 
            {
                dataGridScannedFiles.Columns[i].DisplayIndex = i;

            }
        }

dt is a data table

and I assign him index indices

Now if you use

Int32 columnIndex = dataGridScannedFiles.SelectedCells[0].Column.DisplayIndex;

then you will definitely get an index

+1
source

Source: https://habr.com/ru/post/1789027/


All Articles