• 0

Binding a DataGridView to an IList


Question

Note: While this sample is in VB.NET, I am language agnostic when it comes to a solution (i.e. I'll either code in back up in C# or convert a C# solution)

Setup:

1. Class with three properties, Firstname, Lastname, Age

2. Create 5 instances and add then to a List(of Class)

3. Set the List as the datasource for a DataGridView(setup as read only)

4. By default, the datagridview displays three columns and five rows

Question, is there a way to mark (via an attribute for example) the Age property in TestClass so it does not automatically bind/display in the grid?

   
   Dim foo As New List(Of TestClass)

   For i As Integer = 1 To 5
	 foo.Add(New TestClass("FirstTest " & i.ToString(), "LastTest " & i.ToString(), i))
   Next

   Me.DataGridView1.DataSource = foo

I thought I could do it by marking the age property as

   <System.ComponentModel.Bindable(False)> _
   Public Property Age() As Integer
	 Get
	   Return _age
	 End Get
	 Set(ByVal value As Integer)
	   _age = value
	 End Set
   End Property

But that didn't work, it still gets bound (at least visually)

Link to comment
https://www.neowin.net/forum/topic/599628-binding-a-datagridview-to-an-ilist/
Share on other sites

6 answers to this question

Recommended Posts

  • 0

You need to set up a Binding source, and then bind the list to the binding source and then the datagridview to the binding source:

Once you do this, you can then manipulate the datagridview using the IDE to show and hide those columns that you want to display, and which columns of the binding source you want to bind to what when displaying them

  • 0
  ramesees said:
You need to set up a Binding source, and then bind the list to the binding source and then the datagridview to the binding source:

Once you do this, you can then manipulate the datagridview using the IDE to show and hide those columns that you want to display, and which columns of the binding source you want to bind to what when displaying them

Thats what I am trying to avoid. I would prefer to have the data dictate what is visible if possible. By the way, the List will bind to the grid just fine without overhead of the BindingSource object.

  • 0

The DataGridView control contains the property 'AutoGenerateColumns', which will cause the control to generate a column for each public property and/or field. Set this to false, but you will need to manually create your columns and binding settings.

  • 0

Antaris, that is what I did (in a way). I landed up using a custom attribute to mark each property then created a re-usable grid fill routine that would only add the data to a grid that was marked 'bindable'. I was just looking for a shortcut...

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.