2017-11-17 154 views
0

我嘗試在datagridview標題單元下方打開表單。我有這樣的(和它不工作)datagridviewcell下的打開表格

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(); 
} 

我不知道如何得到正確的頂部和左側基於DataGridView的單元格。

回答

2

你應該考慮到使用的一種形式,你必須使用屏幕座標來計算其位置:

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); 

如果您使用表單麻煩找youself,你可以考慮使用一個面板來代替:

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(); 

也看看thisthis

+0

感謝,這工作。 – Hansvb