title: c# How to reference a dynamically created Combo box?
body: <p>I have some code that creates a few combo boxes on the click of a button. Something like this.</p>
  
  <pre><code>for (int i =0; i&lt; noCol;i++){
  tableLayoutPanel2.RowCount = tableLayoutPanel2.RowCount + 1;
  tableLayoutPanel2.Controls.Add(new Label() { Text = "العمود " + (i+1) }, 0, (i));
  var com = new ComboBox();
  com.Name = "reportColumn" + (i + 1).ToString();
  g = tableLayoutPanel2.Controls[com.Name] as ComboBox;
  c.Add(g);
  g.SelectedIndexChanged += new EventHandler(ReportWizardStep1ComboboxSelectedIndexchanged);
  tableLayoutPanel2.Controls.Add(com,1,i);}
  
  private void ReportWizardStep1ComboboxSelectedIndexchanged(object sender, EventArgs e){ComboBox combo = sender as ComboBox;
  MainForm.exportReport.getDataGridView1().ColumnCount++;
  MainForm.exportReport.getDataGridView1().Columns
              [MainForm.exportReport.getDataGridView1().ColumnCount - 1].HeaderText = g.Text;
  comboValues.Add(g.Text);}
  </code></pre>
  
  <p>but, when I run the code, an exception is thrown for this line:</p>
  
  <pre><code>g.SelectedIndexChanged += new EventHandler(ReportWizardStep1ComboboxSelectedIndexchanged);
  tableLayoutPanel2.Controls.Add(com,1,i);
  </code></pre>
  
  <p>the exception is : </p>
  
  <blockquote>
    <p>An exception of type 'System.NullReferenceException' occurred. how can I solve this problem</p>
  </blockquote>