blah blah blah is here! blah blah » Close

up0down
link

How can I get the position of a certain cell of a datagridview. To be specific I don't want the mouse coordinates. Suppose I have a datagridview with Name (ReadOnly), ID and TransDate columns and I want to popup a tiny lookup form when the mouse is clicked or Enter button is pressed when the focus is upon the Name column. The lookup form should openup exactly upon the Name column of the selected row. Thanks.

last answered one year ago

3 answers

up0down
link

I'd suggest that you handle the DGV's CellMouseClick and KeyDown events.

The code to put in the eventhandlers will be as follows:

private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex > - 1 && dataGridView1.Columns[e.ColumnIndex].Name == "Name")
{
// call method to show your lookup form
}
}

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (dataGridView1.CurrentCellAddress.X == dataGridView1.Columns["Name"].Index && e.KeyData == Keys.Enter)
{
e.Handled = true;
// call method to show your lookup form
}
}

Thanks, but if u see carefully then I already know how to open the form. That's not what I wanted to know. I want to get the exact position of the cell. Anyway I got a solution posted below. Regards.

up0down
link

Here's a solution I came up to.
I am opening a dialog form above the datagridview form. In Form1 I have a datagridview containing few columns among which is 'TransDate' column having index 8. When I click on it, frmDate opens up exactly on it. My revised code follows:


Private Sub DataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridview1.CellClick
If DataGridview1.CurrentCell.OwningColumn.Name = "TransDate" Then
Dim objPoint As Point

'Getting the exact location of the cell with respect to Form1.
'Note- Me.Location is added here alongwith DataGridView1.Location and DataGridView1.GetDisplayRectangle().Location.
'This is done because the form frmDate we are calling is external to Form1 and if we don't add Me.Location
'here, frmDate won't open exactly at the desired point if we move or resize Form1. Instead of frmDate if
'we use any control inside Form1 to place over 'TransDate' column then remove Me.Location here and the
'next two lines.
objPoint = (Me.Location + DataGridview1.Location + DataGridview1.GetCellDisplayRectangle(8, DataGridview1.CurrentCellAddress.Y, True).Location)

'Setting the exact location where frmDate will be opened. The last digits may vary according to your
'requirement.
objPoint.X = objPoint.X - 158
objPoint.Y = objPoint.Y + 28

objFrmDate = New frmDate()
objFrmDate.Location = objPoint
objFrmDate.ShowDialog(Me)
objFrmDate = Nothing
End If
End Sub


Regards.

Feedback