Saturday, 29 January 2011

Adding a RadContextMenu to a Command Button in RadGridView

Out-of-the-box, the RadGridView does a really good job of manking context menus in the RadGridView a simple process by handling the ContextMenuOpening event handler.

If however you have a GridViewCommandColumn in your RadGridView and you want to add a context menu to your command button, then the ContextMenuOpening event doesn't fire for this, as the command button is a RadButtonElement inside the CellElement.

it is though, quite a simple process to add a RadContextMenu to a command button.

  • Subscribe to the CellFormatting event and add a MouseDown event handler on the command button

    Private Sub RadGridView1_CellFormatting(ByVal sender As System.Object,
                                            ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView1.CellFormatting

        If TypeOf e.CellElement Is GridCommandCellElement Then
            If e.CellElement.Tag Is Nothing Then
                AddHandler CType(e.CellElement, GridCommandCellElement).CommandButton.MouseDown, AddressOf Button_MouseDown
            End If
            e.CellElement.Tag = True
        End If
    End Sub

  • Handle the MouseDown event, and create your context menu
    Private Sub Button_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
        If e.Button = MouseButtons.Right Then
            Dim menu As New RadContextMenu()

            Dim item1 As New RadMenuItem("Menu Item 1")
            RemoveHandler item1.Click, AddressOf Item_Click
            AddHandler item1.Click, AddressOf Item_Click
        End If
    End Sub

  • And lastly, handle the click of the context menu
    Private Sub Item_Click(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show("You clicked the item menu in row: " & Me.RadGridView1.CurrentRow.Index.ToString() &
       " cell: " & Me.RadGridView1.CurrentColumn.Index.ToString())
    End Sub

No comments:

Post a Comment