10

I generate all my columns in a subclassed DataGridView programmatically. However Visual Studio 2008 keeps reading my constructor class (which populates a DataTable with empty content and binds it to the DataGridView) and generates code for the columns in the InitializeComponent method - in the process setting AutoGenerateColumns to false.

This causes errors in design-time compilation which are only solved by manually going into the design code and deleting all references to these autogenerated columns.

How can I stop it doing this?

I have tried:

  • Making the control 'Frozen'
  • Setting the DataGridView instantiated object protected (suggested in a previous post which referred to this site)

10 Answers 10

5

It sounds like you are adding controls in the constructor. Perhaps add the columns slightly later - perhaps something like overriding OnParentChanged; you'll then be able to check DesignMode so you only add the columns during execution (not during design).

0
5

I've seen this behavior before for ComboBox's with the Items property and it's really frustrating. Here's how I've gotten around it with ComboBox. You should be able to apply this to the DataGridView.

I created a "new" property called Items and set it to not be browsable and to be explicitly be hidden from serialization. Under the hood it just accesses the real Items property.

[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new ObjectCollection Items
{
    get { return ((ComboBox)this).Items; }
}

[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new object DataSource
{
    get { return ((ComboBox)this).DataSource; }
3
  • I see what you are trying however when I try to adapt this to a subclassed DataGridView it fails. Should there be 'override' in there?
    – Brendan
    Feb 10, 2009 at 20:07
  • You'll have to customize it for DataGridView's Columns. This is just a cut/paste from a ComboBox sample I have. Definately don't want to override as nothing here is virtual
    – JaredPar
    Feb 10, 2009 at 21:07
  • It's the first time I see the attribute 'DesignerSerializationVisibility'. Very nice feature... I will integrate it in a couple of my framework components. Thank you JaredPar.
    – Samuel
    Jun 27, 2012 at 18:44
2

I ran into a problem similar to this, and am posting my solution here since when I wrote my question this was the top suggested question. Each time I compiled my code the designer would add each of the columns in the datasource automatically (and the next time I built my code they'd appear in the running app) despite autogenerate columns being set to false.

Eventually I managed to stop it by giving one of my columns the same name that the auto-generated column had (my columns had originally been created manually before the datasource was available).

1

Mark was right. The Designer looks at the constructor for this autogenerating behaviour. Here is how I got around it.

Took the code which constructs/binds the DataTable to the DataGridView out of the constructor and placed it in a method.

Using the Load event on the containing form - which holds multiple DataGridViews call the BindData() method on each instance,


List<Control> childControls = Misc.Misc.GetAllChildControls(this);
foreach (Control ctrl in childControls) {
    if (ctrl is WorksheetGridView) {
         WorksheetGridView wsgv = ctrl as WorksheetGridView;
         wsgv.BindData();
    }
}

where GetAllChildControls is a method in a helper class


internal static List<Control> GetAllChildControls(Control topControl)
{
    List<Control> ctrlStore = new List<Control>();
    ctrlStore.Add(topControl);
    if (topControl.HasChildren)
    {
        foreach (Control ctrl in topControl.Controls)
        {
            ctrlStore.AddRange(GetAllChildControls(ctrl));                }
        }
    }
    return ctrlStore;
}

Sorry if this is explicit but I never want to forget how to do this!

1
  • careful with this, x64 applications in debugger swallow exceptions that are thrown from form_Load methods Oct 26, 2013 at 0:10
1

JaredPar's suggestion worked for me:

public partial class RefusjonsOppgjorGrid : DataGridView
{
    public RefusjonsOppgjorGrid()
    {
        InitializeComponent();
    }

    [Browsable(false)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public new DataGridViewColumnCollection Columns
    {
        get{ return base.Columns;}
    }
}
0

I do this often in my custom controls, if you wrap the code you don't want to execute in the designer in a DesignMode check, it should fix your problems.

    if (!DesignMode)
    {
        // Your code here
    }
1
  • I wrapped the code where I populate the DataTable and Bind it to the DataGridView in the above but unfortunately it did not work
    – Brendan
    Feb 10, 2009 at 20:18
0

This is an old questions now but it is still a problem in 2014 with VS2013.

I had a DataGridView with its DataSource set to a BindingSource which in turn had another BindingSource as its DataSource. To solve my issue I didn't need to change anything else other than moving the DataGridView.DataSource assignment into an OnControlCreate override on the form.

0

@JaredPar's answer got me most of the way to solving this, but any controls which contained my DataGridView subclass would add the columns whenever anything in the designer changed.

I wanted to keep the columns in the constructor so they could be seen in the visual designer, so I had to disable the standard DataGridViewDesigner that my subclass inherited from its base, ie. I changed the Designer attribute for my class...

using System.Windows.Forms.Design;

[Designer(typeof(ControlDesigner))]
public class SpecificDataGridView : DataGridView
{
    [Browsable(false),
     DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public new DataGridViewColumnCollection Columns
    {
        get { return base.Columns; }
    }

    ...etc...
}

It does mean that designers can't use the 'Edit Items' et al in the DataGridViewDesigner tasks and they couldn't adjust the properties of the columns should they want to, but for my needs, that wasn't particularly useful so it was no loss.

Anyway, that fixed the problem and it still meant that the columns were visible in the designer which was my primary goal here.

Just thought I'd share.

0

Since this still seems to be a question for some, including myself until a few days ago, I thought I'd post my solution, and the one I'm teaching to students in my classes from this point forward:

First, I create a DataGridView (DGV) object and create the columns in design view, taking note of the object name for the particular column.

Now, when I want to bind data from my database (SQL Server, for this code). I alter the column objects and bind each column directly to the data from the DataTable.

private void FillAddresses()
    {
        // erase any old data
        if (AddrTable != null)
            AddrTable.Clear();
        else
            AddrTable = new DataTable();

        // switch-case for panel types that need an address
        switch(PanelType)
        {
            case "Customer":
            case "Customers":
            case "Location":
            case "Locations":
            case "Employee":
            case "Employees":
                BuildStateColumnChoices();
                SqlCommand sqlAddrCmd = new SqlCommand();
                sqlAddrCmd.CommandText = "exec SecSchema.sp_GetAddress " + PanelType +
                    "," + ObjectID.ToString(); // Fill the DataTable with a stored procedure
                sqlAddrCmd.Connection = DBConnection;
                sqlAddrCmd.CommandType = CommandType.Text;
                SqlDataAdapter sqlDA = new SqlDataAdapter(sqlAddrCmd);

                try
                {
                    sqlDA.Fill(AddrTable);

                    dgvAddresses.AutoGenerateColumns = false;
                    // Actually, you set both the DataSource and DataPropertyName properties to bind the data
                    dgvAddresses.DataSource = AddrTable;

                    // Note that the column parameters are using the name of the object from the designer.
                    // This differs from the column names.
                    // The DataProperty name is set to the column name returned from the Stored Procedure
                    dgvAddresses.Columns["colAddrType"].DataPropertyName = "Type";
                    dgvAddresses.Columns["collAddress"].DataPropertyName = "Address";
                    dgvAddresses.Columns["colAptNum"].DataPropertyName = "Apt#";
                    dgvAddresses.Columns["colCity"].DataPropertyName = "city";
                    dgvAddresses.Columns["colState"].DataPropertyName = "State";
                    dgvAddresses.Columns["colZIP"].DataPropertyName = "ZIP Code";

                }
                catch(Exception errUnk)
                {
                    MessageBox.Show("Failed to load address data for panel type " +
                        PanelType + "..." + errUnk.Message, "Address error",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                break;
        }
    }

For the above code, the DBConnection is a public property for the object that I took this code from, which stored the SqlConnection object. Further, colAddressType was a ComboBox column. Data from the bound DataTable can only match information that is listed in the ComboBox. Similarly, colState is a ComboBox column, but the default values for this box are added by querying another table that contains all the states (in the United States, for this example).

The point here is that you can bind the data you want to include in a DGV by creating the columns at design time, and then binding your data from your DataTable to the columns directly. This allows you to have any type of column you want, rather than just the default TextColumn that is given to you by the default binding mechanism.

It should be noted that, in this case, the DataTable is the result of a stored procedure and that editing in this case is not likely. I tried to use a View as well as a stored function; the first didn't allow editing either (at least, not easily...I suspect I needed an insert before trigger somewhere, but that is a database question), while the second wouldn't return the table based on some issue with dynamic table generation.

0

Re-open the form in the designer so that the columns are auto-generated, then click on the DataGridView, select Edit Columns, go through each offending column and set it's 'Visible' property to False. Re save and close/re-open the form to ensure it's not happening anymore. This was the only non-coding solution that actually worked for me and I didn't want to be adding code to solve what is a winforms designer issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.