开发者

(WPF Datagrid) How do I determine the Column Index of an Item

How do i return the column index of an item within a WPF Datagrid, when I click开发者_开发百科 on a cell I'm using Visual Studio 2010/VB.Net


You can use below code directly to get selected cells column index.

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


You tried use this at the Event Click for Column Index?

int columnIndex = dataGrid.CurrentColumn.DisplayIndex;

I'm using this code in MouseDoubleClick Event or PreviewKeyUp and works perfectly.


Everybody tells about this solution

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

and yes it works but nobody tells that we have to set the Display index first fro every column, maybe it is quite obvious for Experts to get that, but for novices, it's an unfamiliar thing

There are two ways to set it:-

  1. You can set it in XAML part.

I don't know how to set it for custom columns like

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

so I preferred the other Way

  1. Created A function

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

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

dt is my Data Table

and I am assigning Display Indexes to it

Now if you use

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

then You will surely Get the Index


DataGridCells do not have a Click event, they have a Selected event but that is normally fired for each cell in a row when you click on a cell. GotFocus might be a better choice.

e.g.

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

and:

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

DataGridCell.Column.DisplayIndex seems to return an appropriate index, if it somehow is not enough you can use DataGrid.Columns.IndexOf(DataGridCell.Column).


To Get the Column index of particular column name from DataGrid (in wpf using linq)

  int index = DataGrid.Columns.Single(c => c.Header.ToString() == "Department").DisplayIndex;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜