Russell Bearden
Russell Bearden

Reputation: 178

How to prevent designer column replication when using extended DataGridView control that adds columns?

I am creating a DataGridView inherited control that performs some stylizations and also adds a number of columns. The problem is that when this control is added to another form, the designer sees that the Columns property does not match its default value and so adds column generation to the designer in the new form.

To illustrate the problem. Take the following control:

class CustomDataGridView : DataGridView
{
    public CustomDataGridView()
    {
        Columns.Clear();
        Columns.Add("Column", "Header");
    }
}

The Columns.Clear() is unnecessary - it's just there to illustrate that the problem is not the constructor. Anyhow, add the control it to a form. Cause the form UI to reload (by e.g. resizing the datagridview) and the designer ends up constantly adding a new column. I've tried a variety of ideas with no result. I attempted to hide the columns property from the designer, but unfortunately as it's not virtual that's also a no go.

Any ideas? I feel like I must be missing something simple since this is presumably a fairly common usage pattern. I could just add the columns at runtime, but ideally I'd like to keep them visible/editable in the designer.

Upvotes: 1

Views: 93

Answers (1)

Russell Bearden
Russell Bearden

Reputation: 178

The idea I mentioned in the question does actually seem to work fine just using not-really-hiding the property hiding:

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public new DataGridViewColumnCollection Columns { get => base.Columns; }

That solves all the issues of wanting to be able to see and interact with the columns in the designer and since the columns in this control are not intended to be modified it's acceptableish - but is there a way to actually add columns without a hack like this?

Upvotes: 1

Related Questions