nightcoder nightcoder - 2 months ago 9
C# Question

DataGridView AutoGenerateColumns is set to true somehow

I derive DataGridViewEx class from DataGridView like this:

public class DataGridViewEx : DataGridView
{
// ...

[DefaultValue(false)]
[Browsable(true)]
public new bool AutoGenerateColumns
{
get { return base.AutoGenerateColumns; }
set { base.AutoGenerateColumns = value; }
}

public DataGridViewEx()
{
AutoGenerateColumns = false;
}

// ...
}


But, when I add my DataGridViewEx control to a form, I see that AutoGenerateColumns property is set to true! My code doesn't set it to true anywhere, so "someone else" :) sets it to true. Of course the code listed above is executed and AutoGenerateColumns is set to false for a moment, but later it becomes "true".

Any ideas?

Answer

I downloaded .NET sources to be able to debug .NET framework as explained here:
http://referencesource.microsoft.com/serversetup.aspx

Then I put a breakpoint on DataGridView.AutoGenerateColumns property and found out that it is set to true in System.Windows.Forms.Design.DataGridViewDesigner.Initialize() method.
I opened this method in reflector and saw the following:

public override void Initialize(IComponent component)  
{
  ...
  view.AutoGenerateColumns = view.DataSource == null;
  ...
}

So, as DataSource is null, Initialize() method sets AutoGeneratedColumns to true :(

I wanted to derive my own designer from DataGridViewDesigner class to override this behavior, but DataGridViewDesigner is internal, so I can't.

So it seems like there is no way to solve this problem properly :(