The blog has moved to a new address. The blog is now located at http://devintelligence.com

Adsense

Wednesday, May 17, 2006

Sample of Using HitTestInfo Object

The following sample demonstrates how to implement the grid row's popup menu. This menu has only one item, which deletes the row that the menu has been called for. The HitTest method is called to obtain the row position. Selection is then moved to this row and the custom context menu called.


private void dataGridView1_MouseDown(object sender, MouseEventArgs e)

{

System.Windows.Forms.DataGridView.HitTestInfo hitInfo = dataGridView1.HitTest(e.X, e.Y);


if ( (hitInfo.Type == DataGridViewHitTestType.Cell) &&

((e.Button & MouseButtons.Right) != 0) )

{

// switch selection

DataGridViewRow selectedRow = dataGridView1.Rows[hitInfo.RowIndex];

selectedRow.Selected = true;




//show the context menu

ContextMenuStrip contextMenu = new ContextMenuStrip();

contextMenu.Items.Add("Delete Row", null, new EventHandler(DeleteSelectedRow) );

contextMenu.Items[0].Tag = selectedRow;

contextMenu.Show(this.dataGridView1, e.X, e.Y);

}

}




private void DeleteSelectedRow(object sender, EventArgs e)

{

ToolStripItem menuItem = sender as ToolStripItem;

if (menuItem != null)

{

dataGridView1.Rows.Remove(

(DataGridViewRow)menuItem.Tag

);

}

}

Technorati : , , , , ,
Ice Rocket : , , , , ,

No comments: