Search code examples
wpfwpfdatagrid

WPF DataGrid AutoGeneratingColumn event returns -1 for all ColumnDisplayIndex


The following code returns -1 for each displayed column.

Anyone knows the answer? I tried to use ColumnDisplayIndexChanged event. But it did not show anything.

i.konuk

private void dg_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            string headername = e.Column.Header.ToString();

            //Cancel the column you don't want to generate
            if (headername == "Occupation")
            {
                e.Cancel = true;
            }

            //update column details when generating
            if (headername == "FirstName")
            {
                e.Column.Header = "First Name";
            }

            //update column details when generating
            if (headername == "LastName")
            {
                e.Column.Header = "Last Name";
            }

            int myin = e.Column.DisplayIndex;

            System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder();
            messageBoxCS.AppendFormat("{0} = {1}", "Column", myin);
            messageBoxCS.AppendLine();
            MessageBox.Show(messageBoxCS.ToString(), "DataGridAutoGeneratingColumnEvent");

        }

Solution

  • AutoGeneratingColumn event occurs when an individual column is auto-generated in other words the event is called when columns are forming in the dataGrid. This means no columns are displayed yet.

    DataGridColumn.DisplayIndex property displays the position of the column in the DataGrid. We have not yet displayed the columns in AutoGeneratingColumn event. The DisplayIndex property has a default value of -1 before it is added to the DataGrid.Columns collection. Thats why you are getting the default value of -1.

    ColumnDisplayIndexChanged Event is called when you have selected a particular column and changed the dispayed order in the DataGrid.

    Hope I have answered your Question!