title: c# binding datagridview to datatable in form vs control
body: <p>I have the following code:</p>
  
  <pre><code>        DataGridView lGrid = new DataGridView();
          BindingSource _bind = new BindingSource();
          DataTable Table = new DataTable();
  
          this.Controls.Add(lGrid);
          lGrid.AutoGenerateColumns = true;
  
  
          List&lt;string&gt; ColumnsNames = new List&lt;string&gt;();
          ColumnsNames.Add("ID");
          ColumnsNames.Add("NAME");
  
          foreach (string Name in ColumnsNames)
              Table.Columns.Add(Name);
  
          DataColumn col = Table.Columns["ID"];
          DataColumn[] keys = new DataColumn[1];
          keys[0] = Table.Columns["ID"];
          Table.PrimaryKey = keys;
  
          lGrid.DataSource = _bind;
          _bind.DataSource = Table;
  
          int i = lGrid.Columns.Count;
  </code></pre>
  
  <p>which populates lGrid with columns in datatable just fine with this code executing in the form constructor. However, when I move it to the control constructor binding doesn't work and i = 0. Why is it so and what can i do about it?</p>
  
  <h1>Update1</h1>
  
  <p>OK. the constructors are the most simple</p>
  
  <p>public partial class Form1 : Form
      {</p>
  
  <pre><code>    public Form1()
      {
            InitializeComponent();
           //CODE GOES HERE
      }
  }
  </code></pre>
  
  <p>VS</p>
  
  <pre><code>public class mycontrol : Control
  {
      public mycontrol()
      {
          //CODE GOES HERE
      }
  }
  
  
  public partial class Form1 : Form
  {
  
      public Form1()
      {
            InitializeComponent();
  
            mycontrol ll = new mycontrol();
            this.Controls.Add(ll);
      }
  }
  </code></pre>