简体   繁体   中英

How can i bind a generic List of custom classes to a datagridview and only show specific properties in VB.NET?

I would like a way to present custom classes in a datagridview in a custom way that I have full control of. For example if I simply bind the List to the datagridview now, a column for each public property will be created. Even if I utilize the DataPropertyName property of the DataGridViewTextBoxColumn, additional columns for each additional property of the custom class is created.

I know that I can simply populate the datagridview myself, but even being a VB.NET beginner, I feel that that is not a good solution. Is it?

I think I remember that it is possible to implement some interface that helps specify exactly how a the class is represented in a datagridview control.

Can some one point me towards the best and most efficient solution?

DataGridView have AutoGenerateColumns property which by default is True . Set it to False and specify the columns that you want under DataGridView -> Columns tag

You can make use of the Browsable attribute .

If you bind a List of the following class to a DataGridView

Class Person

    Public Property Name As String

    Public Property Department As String

    <System.ComponentModel.Browsable(False)>
    Public Property SomethingInternal As String

End Class

only the Name and Department column would be created.

Quick example:

Using f As New Form
    Dim g = New DataGridView With {
        .Dock = DockStyle.Fill,
        .DataSource = { New Person With 
                        { 
                            .Name = "Foobar", 
                            .Department = "BarFoo", 
                            .SomethingInternal = "Don't show this"
                        }}}
    f.Controls.Add(g)
    f.ShowDialog()
End Using

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM