Jorge Perez
Jorge Perez

Reputation: 47

Why does the AutoGeneratingColumn event in a DataGrid repeat the columns?

When I search in a list I pass the result to a function to load the DataGrid Each time the AutoGeneratingColumn event is fired, it repeats the same column once more. When starting the application, the event checks the column once, doing the first search checks twice, with the second three times and so on. I have the next function to load the DataGrid:

private void cargarListaAgenda(List<listaAgendaClass> lista)
{
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
    {
        gridAgendaDataGridAgenda.AutoGeneratingColumn += (s, e) =>
        {
            e.Column.Visibility = Visibility.Hidden;

            if (e.Column.Header.ToString() == "Nombre" || e.Column.Header.ToString() == "Alias" || e.Column.Header.ToString() == "Apellidos")
            {
                e.Column.Visibility = Visibility.Visible;

                if (e.Column.Header.ToString() != "Apellidos")
                    e.Column.Width = new DataGridLength(gridAgendaDataGridAgenda.Width * 0.33);

                else
                    e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            }
        };

        gridAgendaDataGridAgenda.ItemsSource = null;
        gridAgendaDataGridAgenda.ItemsSource = lista;
    }));
}

Upvotes: 0

Views: 511

Answers (1)

mm8
mm8

Reputation: 169410

It seems like you are attaching a new event handler each time your cargarListaAgenda method is called.

Try to remove the event handler before you attach a new one:

private void cargarListaAgenda(List<listaAgendaClass> lista)
{
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
    {
        gridAgendaDataGridAgenda.AutoGeneratingColumn -= GridAgendaDataGridAgenda_AutoGeneratingColumn;
        gridAgendaDataGridAgenda.AutoGeneratingColumn += GridAgendaDataGridAgenda_AutoGeneratingColumn;

        gridAgendaDataGridAgenda.ItemsSource = lista;
    }));
}

private void GridAgendaDataGridAgenda_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    e.Column.Visibility = Visibility.Hidden;

    if (e.Column.Header.ToString() == "Nombre" || e.Column.Header.ToString() == "Alias" || e.Column.Header.ToString() == "Apellidos")
    {
        e.Column.Visibility = Visibility.Visible;

        if (e.Column.Header.ToString() != "Apellidos")
            e.Column.Width = new DataGridLength(gridAgendaDataGridAgenda.Width * 0.33);

        else
            e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
    }
}

Upvotes: 1

Related Questions