Search code examples
c#winformsvisual-studio-2010datagridviewmouseclick-event

DataGridView not being created


I have a datagridview with a clickevent assigned to it. This datagridview is on a tabpage. When the user clicks the datagridview, I want a second datagridview to be created below it. This is the code for the click event. The only line that is functioning properly is the Console.WriteLine("dataGridView1 clicked") line. Everything else is being ignored.

void dataGridView1_Click(object sender, EventArgs e)
{
    DataGridView dataGridView1 = new DataGridView();
    dataGridView1.ColumnCount = 6;

    DataGridViewColumn column1 = new DataGridViewColumn();
    column1 = dataGridView1.Columns[0];
    dataGridView1.Columns[0].HeaderText = "column";

    tabPage.Controls.Add(dataGridView1);

    Console.WriteLine("dataGridView1 Clicked");
}

Solution

  • It could be getting created under the current DataGridView or under some elements within the form. Add a panel to your layout where you would like the DataGridView to be added and try adding it to that Panel and it should work.

    Drag and drop a panel from the toolbox on to your form and then in the dataGridView1_Click event, add the control to the panel.

    panel1.Controls.Add(dataGridView2);