1

I try to open a form just below a DataGridView header cell. I have this (and it is not working):

private void button1_Click(object sender, EventArgs e)
{
    Form aForm = new Form();

    aForm.Text = @"Test";
    aForm.Top = this.Top + dataGridView1.Top - dataGridView1.GetCellDisplayRectangle(0, 0, false).Height;
    aForm.Left =  this.Left + dataGridView1.GetCellDisplayRectangle(0, 0, false).Left;
    aForm.Width = 25;
    aForm.Height = 100;
    aForm.ShowDialog();
}

I don't see how to get the right top and left based on the DataGridView cell.

Shams Tech
  • 105
  • 8
Hansvb
  • 113
  • 1
  • 1
  • 13

1 Answers1

2

Should you consider to use a Form, you have to calculate its Location using Screen coordinates:

Form form = new Form();
form.StartPosition = FormStartPosition.Manual;
form.FormBorderStyle = FormBorderStyle.FixedSingle;
form.Size = new Size(dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Width, 100);

Point c = dataGridView1.PointToScreen(dataGridView1.GetCellDisplayRectangle(
                                      dataGridView1.CurrentCell.ColumnIndex, 
                                      dataGridView1.CurrentCell.RowIndex, false).Location);
form.Location = new Point(c.X, c.Y);
form.BringToFront();
form.Show(this);

If you find youself in trouble using a Form, you might consider using a Panel instead:

Point c = dataGridView1.PointToScreen(dataGridView1.GetCellDisplayRectangle(
                        dataGridView1.CurrentCell.ColumnIndex, 
                        dataGridView1.CurrentCell.RowIndex, false).Location);
Point r = this.PointToClient(c);
panel1.Location = new Point(r.X, r.Y);
panel1.BringToFront();

Take also a look at How do I to get the current cell position x and y in a DataGridView?
and Position new form directly under Datagridview selected row of parent

Jimi
  • 29,621
  • 8
  • 43
  • 61