0
votes

I have a datagrid in my WPF application and i am binding an Ienumerable collection to the itemsource of the datagrid.

I need to add a handler for AutoGenerated columns in DataGrid after binding it. But i can't.

this.dataGrid1.ItemsSource = ineumerable_collection;
dataGrid1.AutoGeneratedColumns += new EventHandler(dataGrid1_AutoGeneratedColumns);//Not working

I have set Autogeneratecolumns as True in my XAML. But when i run my application it is not invoking the event handler dataGrid1_AutoGeneratedColumns. Thanks in advance if u could solve my problem!

3

3 Answers

0
votes

The problem is that you're attaching the event handler after you've changed the ItemsSource, which means the columns get generated before your handler is attached. Just switch the order of the two statements.

dataGrid1.AutoGeneratedColumns += new EventHandler(dataGrid1_AutoGeneratedColumns);
this.dataGrid1.ItemsSource = ineumerable_collection;
0
votes

But when i run my application it is not invoking the event handler

You should first subscribe to the event:

dataGrid1.AutoGeneratedColumns += dataGrid1_AutoGeneratedColumns

and then change items source:

this.dataGrid1.ItemsSource = ineumerable_collection;

because this event raised after ItemsSource changed and the last column was generated.

0
votes

According to MSDN:

The AutoGeneratedColumns event is raised every time the DataGrid attempts to generate columns.For example, AutoGeneratedColumns is raised when the DataGrid is initialized, AutoGenerateColumns is set to true, or the ItemsSource is changed, even if the ItemsSource is null.

Try to subscribe on an event before setting ItemsSource.