Post navigation

HOWTO create a Pop-up menu (context menu) for single cell of a datagrid

Recently I needed fo find a way for a user to be presented with a list of possible values, but to also be able to ignore that list and enter their own value into a datagrid cell. I figured I could just use a combo box column (dropdownlist) and it would behave the same way as a combobox does when it is on a form (not within a datagrid). In that situation the user can just enter a value into the text portion of the combo box assuming they did not like any of the options in the box itself. Well, that’s not the way a comboboxcolumn works… you choose from the list it makes available… that’s all you get for free.

Unfortunately, that was not an option. I had to allow the user to enter their own value if they didn’t see the one they wanted in the list. So, what I did was I set the column up as a regular Text based column. Then I implemented a pop-up menu that showed when the user right clicked on a cell in a particular column. Before popping up it determines what the correct menu items for cells in the columns in which it resides and then makes those options available to the user. It took me a little while to figure out – hopefully this will save someone some time.

My sample code below is in VB. Basically it makes use of the fact that when in a datagrid a right click causes “CellContextMenuStripNeeded” to be fired. So we build up our menu strip there. You could ofcourse also have a static menustrip and set striptoShow directly to it rather than building up stripToShow everytime.

”””””””””””””””’ SET UP SOME PRIVATE VARIABLES WE WILL NEED ””””””””””””””’

If (theCellImHoveringOver .ColumnIndex = -1) Then Return‘ nothing special to pop up hereEndIf

If (dgv.Columns(theCellImHoveringOver.ColumnIndex).Name = “Column_Name_Here”) Then If (dgv.Rows(theCellImHoveringOver.RowIndex).Cells(“Column_Name_Here”).Selected) Then �
‘ NOTE: I only want it to do this if the cell i right click on is SELECTEDIf stripToShow IsNothingThen stripToShow = New ContextMenuStrip()�stripToShow .Items.Add(“Item1”, Nothing, New System.EventHandler(AddressOfMe.stripToShow _Item_Click))stripToShow .Items.Add(“Item2”, Nothing, New System.EventHandler(AddressOfMe.stripToShow _Item_Click)) ‘NOTE: I added a handler for the click. In my handler I will set the cell value to whatever the user selects from the menu EndIf e.ContextMenuStrip = stripToShow�EndIfEndIf

Catch ex As Exception
MessageBox.Show(“There was an error popping up the menu. Please try again.”)EndTry