title: Using a DataSource with an object in Windows Forms
body: <p>I have been trying to create a small form application and I wanted to try out binding a DataGridView directly to a collection of objects.</p>
  
  <p>I created the following classes</p>
  
  <pre><code>public class MyClassRepository
  {
      public List&lt;MyClass&gt; MyClassList { get; set; } = new List&lt;MyClass&gt; { new MyClass { Name = "Test" } };
  }
  
  public class MyClass
  {
      public string Name { get; set; }
  }
  </code></pre>
  
  <p>and I added the following code to a form to test. I based this off of the code in the designer after setting the BindingSource through the UI (while following this walk through <a href="https://msdn.microsoft.com/en-us/library/ms171892.aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/ms171892.aspx</a>)</p>
  
  <pre><code>var tmp = new BindingSource();
  tmp.DataMember = "MyClassList";
  tmp.DataSource = typeof(MyClassRepository);
  </code></pre>
  
  <p>When this didn't work I started running through the code behind BindingSource to see what was happening. The setter calls <code>ResetList</code> which tries to create a <code>dataSourceInstance</code> by calling <code>ListBindingHelper.GetListFromType</code>. This call ultimately calls <code>SecurityUtils.SecureCreateInstance(Type)</code> where type is a <code>BindingList&lt;MyClassRepository&gt;</code>. This passes null to args which is passed <code>Activator.CreateInstance</code> which returns an empty collection.</p>
  
  <p>After this <code>ListBindingHelper.GetList(dataSourceInstance, this.dataMember)</code> is called. This method calls <code>ListBindingHelper.GetListItemProperties</code> which results in a <code>PropertyDescriptor</code> for my <code>MyClassList</code> property and assigns it to <code>dmProp</code>.</p>
  
  <p>At this point <code>GetList</code> calls <code>GetFirstItemByEnumerable(dataSource as IEnumerable)</code> where dataSource is the previously created (and empty) instance of <code>BindingList&lt;MyClassRepository&gt;</code> and returns <code>(currentItem == null) ? null : dmProp.GetValue(currentItem);</code>.</p>
  
  <p>The value of dmProp/MyClassList is never accessed and the BindingSource is never populated with the instance I created. Am I doing something wrong? If not is there a bug in the source code? It seems to me like either <code>SecureCreateInstance(Type type, object[] args)</code> should be called and MyClassList should be passed via args instead of the existing call to <code>SecureCreateInstance(Type type)</code> or the value of <code>dmProp</code> should be used regardless?</p>
  
  <p>If that is not correct how do I make the Designers automatically generated code set the DataSource to an instance of the object? Or do I have to inherit from BindingSource? If the latter why does it give you the option to choose a class that does not inherit from BindingSource?</p>