Sam Selikoff
Sam Selikoff

Reputation: 12694

How to tell my DataGridView what kind of objects it will display in designer

I have a DataGridView in a user control. I can drag a companies collection (which is an Entity Collection) to the DGV, which creates a CompaniesBindingSource and lets me edit the columns of the DataGridView according to the properties on my Company model.

However, I end up setting the .DataSource of my DGV in my load event, because I want it to use a BindingSource in the parent form.

Since I'm not using the auto-generated BindingSource in my user control, is there a way for my to simply tell my DGV that it will be displaying a list of Company models, without having visual studio automatically setting up the CompaniesBindingSource in the user control?

Upvotes: 0

Views: 370

Answers (1)

In your UserControl create aDataSource and a DataMember property which reflects those of the DataGridView. Then when you drop the control to the form be sure to set both properties.

<Editor("System.Windows.Forms.Design.DataGridViewColumnCollectionEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", GetType(Drawing.Design.UITypeEditor)), MergableProperty(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> _
Public ReadOnly Property Columns() As DataGridViewColumnCollection
    Get
        Return Me.myDataGridView.Columns
    End Get
End Property

<Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", GetType(Drawing.Design.UITypeEditor)), DefaultValue(""), Category("Data")> _
Public Property DataMember() As String
    Get
        Return Me.myDataGridView.DataMember
    End Get
    Set(value As String)
        Me.myDataGridView.DataMember = value
    End Set
End Property

<DefaultValue(CStr(Nothing)), Category("Data"), AttributeProvider(GetType(IListSource))> _
Public Property DataSource() As Object
    Get
        Return Me.myDataGridView.DataSource
    End Get
    Set(value As Object)
        Me.myDataGridView.DataSource = value
    End Set
End Property

<Browsable(False)> _
Public ReadOnly Property Rows As DataGridViewRowCollection
    Get
        Return Me.myDataGridView.Rows
    End Get
End Property

Or you can reflect the DataGridView itselves.

<Category("Controls")> _
Public ReadOnly Property View() As DataGridView
    Get
        Return Me.myDataGridView
    End Get
End Property

Upvotes: 1

Related Questions