views:

384

answers:

3

Hello, 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?
Thank you in advance.

+1  A: 

That's to be expected, unfortunately. Because you're declaring AutogenerateColumns as new, calls to it don't get virtualized. When the parent code sets AutogenerateColumns to true, it does not pass down into your property setter. While this won't have any direct effect upon the behavior (since you don't do anything but defer to the parent property), it does limit your ability to debug since you can't do a Console.WriteLine(Environment.StackTrace) or something similar in your setter.

You will likely need either to use a tool like Reflector to try to find where it's getting set to true, but this will be problematic for all but the simplest of scenarios (for example, if the parent sets the backing variable directly). You'll really need to do some trial and error to find where the value is being set, then call your AutoGeneratedColumns = false; code. I would override OnCreateControl and inspect the value there as a start.

Adam Robinson
+1  A: 

This has been a problem for me as well. For some reason the AutogenerateColumns property has an attribute of [Browsable(false)] so it won't show up in the designer. To work around this, I make sure to set AutogenerateColumns=False in the constructor of the form containing the DataGridView control. I believe that as long as you do this before databinding, it should work as expected.

C-Pound Guru
A: 

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 :(

nightcoder