1

Suppose I have a composite UserControl (called 'ListTable'), consisting of a label, two buttons and a DataGridView. The label is the title for the DataGridView, and the two buttons are Add Row and Delete Row, with basic, obvious functionality.

How do I expose the DataGridView's columns in the Designer, so that I can edit the DataGridView's columns through the UserControl in the exact same way I would if editing the DataGridView itself?

WHAT I'VE TRIED:

Various combinations of wrapping the DataGridView's Columns property in the ListTable via a property titled 'TableColumns' of the form 'List', with various attribute values, such as:

[DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
    [Editor(typeof(TableColumnEditor),
        typeof(System.Drawing.Design.UITypeEditor))]
    public List<DataGridViewColumn> TableColumns
    {
        get
        {
            List<DataGridViewColumn> columns = new List<DataGridViewColumn>();
            foreach (DataGridViewColumn col in table.Columns)
            {
                columns.Add(col);
            }

            return columns;
        }
        set
        {
            this.table.Columns.Clear();

            foreach (DataGridViewColumn col in value)
            {
                this.table.Columns.Add(col);
            }
        }
    }

Where TableColumnEditor is:

class TableColumnEditor : CollectionEditor
{
    public TableColumnEditor(Type type) : base(type) { }

    public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        object result = base.EditValue(context, provider, value);
        ((ListTable)context.Instance).TableColumns = (List<DataGridViewColumn>)result;

        return result;
    }
}

None of this has seemed to work. Most of this is just prayful patchwork that I don't completely understand.

So, the classic dilemma: I do need to sit down and learn about these innards, but I don't have the (work)time to do an unfocused, leisurely tramp through MSDN's more esoteric WinForms articles. Is the code above salvageable? Is it in the right direction?

4

1 回答 1

0

Does this help:

Put a BindingSource on the Form (BindingSource1).

Set your DataGridView's Datasource to Binding1.

Open the designer for the Form in question, and assuming you want to show the columns for the MyObject class, enter the following:

this.BindingSource1.Datasource = typeof(YourNamespace.MyObject);
于 2013-06-27T09:21:23.813 回答