This is a migrated thread and some comments may be shown as answers.

How to create context menu attached to row pogrammatically?

10 Answers 431 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Goran
Top achievements
Rank 1
Goran asked on 19 Dec 2012, 06:54 AM
Hi,

We use Telerik Grid for VS2008 and need to create context menu attached to grid row programmatically. I mean when you right click any row the context menu should show up. The context menu should be multilevel and dynamically populated. Grid control is wrapped into our user control.

Ho can we do that?

Thank you in advance.

Goran

10 Answers, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 19 Dec 2012, 07:09 AM
Hi,

You can populate the menu as shown below.
C#:
RadMenu1.DataTextField = "Id";
RadMenu1.DataValueField = "Id";
RadMenu1.DataSourceID = "SqlDataSource1";
RadMenu1.DataBind();
In order to show the contextmenu, try the following javascript.
aspx:
<ClientEvents OnRowContextMenu="OnRowContextMenu" />
JS:
function RowContextMenu(sender, eventArgs)
{
 var menu = $find("<%=RadMenu1.ClientID %>");
 var evt = eventArgs.get_domEvent();
 menu.show(evt);
}

Thanks,
Shinu.
0
Goran
Top achievements
Rank 1
answered on 19 Dec 2012, 07:35 AM
Thanks for this Shinu.

But, how can we add RadContextMenu programmatically to existing Telerik grid and how should we set it's ID to be "RadMenu1" programmatically? I'm asking this because we can use JavaScript that calls that context menu by its ClientID.
0
Goran
Top achievements
Rank 1
answered on 20 Dec 2012, 06:30 AM
I please someone to help with this issue.

Here's more details about our scenario how we use Telerik's grid:

We wrapped the original Telerik's grid to our control and that wrapped version is used to create new user control - GridFrameControl. Our wrapped control is a member of GridFrameControl. GridFrameControl is derived from standard UserControl.

Our web application has master page and GridFrameControl is placed inside of some content pages. We load GridFrameControl dynamically using the following:

var gridFrameControl = LoadControl("Controls/GridFrameControl.ascx") as GridFrameControl;

So, what I'm trying to do? I'm trying to add RadContextMenu to GridFrameControl in the following way:

public partial class GridFrameControl : ActionFrameControl, IProfileSetting
{
    private RadContextMenu contextMenu;
 
    protected override void OnInit(EventArgs e)
    {
        contextMenu = new RadContextMenu();
        RadMenuItem item1 = new RadMenuItem("MenuItem1");
        RadMenuItem item2 = new RadMenuItem("MenuItem2");
        RadMenuItem item3 = new RadMenuItem("MenuItem3");
        contextMenu.Items.Add(item1);
        contextMenu.Items.Add(item2);
        contextMenu.Items.Add(item3);
        contextMenu.ItemClick += new RadMenuEventHandler(contextMenu_ItemClick);
        Controls.Add(contextMenu);
        ...
    }
    ...
}

But I'm not sure what to do next. Where should I add ASP.NET and JavaScript code? We create pages dynamically.

Thank you in advance.
0
Eyup
Telerik team
answered on 21 Dec 2012, 01:17 PM
Hi Goran,

Please check out the provided web site and demo link in the following thread:
http://www.telerik.com/community/forums/aspnet-ajax/grid/hide-show-certain-radgrid-context-menu-items.aspx

I hope this will prove helpful.

All the best,
Eyup
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
0
Goran
Top achievements
Rank 1
answered on 24 Dec 2012, 12:12 PM
Hi Eyup,

Thank you for trying to help me but that discussion doesn't help in my case. Once again I have user control that contains Telerik's rad grid. I need to add the rad context menu to rad grid dynamically as well. After creating user control I load it dynamically.

The code of user control is as following:

1) Markup:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="GridUserControlDynamic.ascx.cs" Inherits="TelerikGrid.GridUserControlDynamic" %>
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
 
<div style="border:solid 1px Black;">
     
    <telerik:RadScriptManager runat="server" ID="RadScriptManager1" />
 
    <input type="hidden" id="radGridClickedRowIndex" name="radGridClickedRowIndex"/>
 
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
        SelectCommand="SELECT [ContinentID], [ContinentName] FROM [Continent]">
    </asp:SqlDataSource>
 
    <div style="margin-right: 20px;">
        <telerik:RadGrid ID="RadGrid1" runat="server" Width="100%" DataSourceID="SqlDataSource1" AllowAutomaticDeletes="true" AllowAutomaticInserts="true" AllowAutomaticUpdates="true">
            <MasterTableView AllowSorting="False" PageSize="10" AllowPaging="True" Width="100%" DataKeyNames="ContinentID" DataSourceID="SqlDataSource1" EditMode="InPlace">
            </MasterTableView>
            <ClientSettings>
                <ClientEvents OnRowContextMenu="RowContextMenu"></ClientEvents>
                <Selecting AllowRowSelect="true"></Selecting>
            </ClientSettings>
        </telerik:RadGrid>
    </div>
 
</div>

2) Code behind:

public partial class GridUserControlDynamic : System.Web.UI.UserControl, IScriptControl
{
    private ScriptManager sm;
 
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
 
        RadContextMenu contextMenu = new RadContextMenu();
        contextMenu.ID = "RadMenu1";
        RadMenuItem item1 = new RadMenuItem("Add");
        RadMenuItem item2 = new RadMenuItem("Edit");
        RadMenuItem item3 = new RadMenuItem("Delete");
        contextMenu.Items.Add(item1);
        contextMenu.Items.Add(item2);
        contextMenu.Items.Add(item3);
        contextMenu.ItemClick += new RadMenuEventHandler(contextMenu_ItemClick);
        Controls.Add(contextMenu);
    }
 
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
    protected void contextMenu_ItemClick(object sender, RadMenuEventArgs e)
    {
        int radGridClickedRowIndex;
 
        radGridClickedRowIndex = Convert.ToInt32(Request.Form["radGridClickedRowIndex"]);
 
        switch (e.Item.Text)
        {
            case "Edit":
                RadGrid1.Items[radGridClickedRowIndex].Edit = true;
                RadGrid1.Rebind();
                break;
            case "Add":
                RadGrid1.MasterTableView.IsItemInserted = true;
                RadGrid1.Rebind();
                break;
            case "Delete":
                RadGrid1.MasterTableView.PerformDelete(RadGrid1.Items[radGridClickedRowIndex]);
                break;
        }
    }
 
    public RadGrid GridControl
    {
        get
        {
            return this.RadGrid1;
        }
    }
 
    protected override void OnPreRender(EventArgs e)
    {
        if (!this.DesignMode)
        {
            // Test for ScriptManager and register if it exists
            sm = ScriptManager.GetCurrent(Page);
 
            if (sm == null)
                throw new HttpException("A ScriptManager control must exist on the current page.");
 
            sm.RegisterScriptControl(this);
        }
         
        base.OnPreRender(e);
    }
 
    protected override void Render(HtmlTextWriter writer)
    {
        if (!this.DesignMode)
            sm.RegisterScriptDescriptors(this);
         
        base.Render(writer);
    }
 
    #region IScriptControl Members
 
    public IEnumerable<ScriptDescriptor> GetScriptDescriptors()
    {
        return null;
    }
 
    public IEnumerable<ScriptReference> GetScriptReferences()
    {
        ScriptReference reference = new ScriptReference();
        reference.Path = ResolveClientUrl("GridUserControlDynamic.js");
 
        return new ScriptReference[] { reference };
    }
 
    #endregion
}

3) JavaScript:

function RowContextMenu(sender, eventArgs)
{
    var menu = $find("<%=RadMenu1.ClientID %>");
    var evt = eventArgs.get_domEvent();
 
    if (evt.target.tagName == "INPUT" || evt.target.tagName == "A") {
        return;
    }
 
    var index = eventArgs.get_itemIndexHierarchical();
    document.getElementById("radGridClickedRowIndex").value = index;
 
    sender.get_masterTableView().selectItem(sender.get_masterTableView().get_dataItems()[index].get_element(), true);
 
    menu.show(evt);
 
    evt.cancelBubble = true;
    evt.returnValue = false;
 
    if (evt.stopPropagation) {
        evt.stopPropagation();
        evt.preventDefault();
    }
}

The code on ASPX page where I dynamically load user control looks as following:

protected void Page_Load(object sender, EventArgs e)
{
    GridUserControlDynamic gridUserCtrl = LoadControl("~/GridUserControlDynamic.ascx") as GridUserControlDynamic;
    PlaceHolder1.Controls.Add(gridUserCtrl);
}

I'm able to display the user control that contains Telerik's rad grid and select rows, but I'm not able to display the context menu.

Could you, please, take a look at my code and suggest me what I did wrong or what I missed.

I really need make this work.

Thank you.
0
Eyup
Telerik team
answered on 26 Dec 2012, 04:31 PM
Hi Goran,

I have attached a sample RadGrid web site where I implemented the requested functionality. Please check out the attached application and let me know about the result.

All the best,
Eyup
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
0
Goran
Top achievements
Rank 1
answered on 27 Dec 2012, 08:27 AM
Hi Eyup,

Your sample works fine. Thank you very much.

There's only 1 thing left - when we have several web user controls with Telerik's grid on Default.aspx page actions performed on context menu click doesn't raise in appropriate web user control. You can use the project you sent me. Just add 2 lines of code:

Default.aspx:

<asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>

Default.aspx.cs:

WebUserControl1 gridUserCtrl2 = LoadControl("~/WebUserControl1.ascx") as WebUserControl1;
PlaceHolder2.Controls.Add(gridUserCtrl2);

So, how could we resolve this issue?

Goran
0
Eyup
Telerik team
answered on 02 Jan 2013, 12:05 PM
Hi Goran,

In such case, please make the following modification to the user control:
protected void Page_Init(object sender, EventArgs e)
{
    ...
    PlaceHolder1.Controls.Add(contextMenu);
    RadGrid1.ClientSettings.ClientEvents.OnRowContextMenu =
        "function (sender, args) { RowContextMenu(sender, args, $find('" +
    contextMenu.ClientID + "'),$get('" + HiddenField1.ClientID + "')); }";
}
JavaScript:
function RowContextMenu(sender, eventArgs, menu, hiddenField) {
    var evt = eventArgs.get_domEvent();
 
    if (evt.target.tagName == "INPUT" || evt.target.tagName == "A") {
        return;
    }
 
    var index = eventArgs.get_itemIndexHierarchical();
    hiddenField.value = index;
    menu.show(evt);
 
    evt.cancelBubble = true;
    evt.returnValue = false;
 
    if (evt.stopPropagation) {
        evt.stopPropagation();
        evt.preventDefault();
    }
}

That should do the trick. Please let me know about the result when ready.

Kind regards,
Eyup
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
0
Goran
Top achievements
Rank 1
answered on 07 Jan 2013, 06:12 AM
It works!

Thank you very much Eyup
0
Goran
Top achievements
Rank 1
answered on 09 Jan 2013, 08:41 AM
Hi again Eyup,

I've noticed a side effect with context menu in my case. I have simple ASP.NET web application where I've applied the code from your sample. Everything works fine, but when I right click grid header the context menu is shown as well. I don't need it there. I just need the context menu to appear when I right click particular row in the grid. In your sample there's no such side effect.

Here's the markup of my user control:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="GridUserControlDynamic.ascx.cs" Inherits="TelerikGrid.GridUserControlDynamic" %>
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
 
<div style="border:solid 1px Black; width:50%">
     
    <asp:Label ID="Label1" runat="server" Text="Grid User Control" BackColor="Gainsboro"></asp:Label>
    <br />
 
    <input id="Button1" type="button" value="ShowMessage" onclick="showMessage();" />
    <br />
 
    <input type="hidden" id="radGridClickedRowIndex" name="radGridClickedRowIndex"/>
 
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
        SelectCommand="SELECT [ContinentID], [ContinentName] FROM [Continent]">
    </asp:SqlDataSource>
 
    <div style="margin-right: 20px;">
        <telerik:RadGrid ID="RadGrid1" runat="server" Width="100%" DataSourceID="SqlDataSource1" AllowAutomaticDeletes="true" AllowAutomaticInserts="true" AllowAutomaticUpdates="true">
            <MasterTableView PageSize="10" AllowPaging="True" Width="100%" DataKeyNames="ContinentID" DataSourceID="SqlDataSource1" EditMode="InPlace">
            </MasterTableView>
            <ClientSettings>
                <ClientEvents OnRowContextMenu="RowContextMenu"></ClientEvents>
                <Selecting AllowRowSelect="true"></Selecting>
            </ClientSettings>
        </telerik:RadGrid>
    </div>
    <asp:HiddenField ID="HiddenField1" runat="server" Value="0" />
 
</div>
 
Here's the code behind:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
using System.ComponentModel;
using Telerik.Web.UI;
 
[assembly: WebResource("TelerikGrid.GridUserControlDynamic.js", "application/x-javascript")]
 
namespace TelerikGrid
{
    public partial class GridUserControlDynamic : System.Web.UI.UserControl/*, IScriptControl*/
    {
        public RadContextMenu contextMenu = new RadContextMenu();
 
        protected void Page_Init(object sender, EventArgs e)
        {
            ContextMenuControlTarget target = new ContextMenuControlTarget();
            target.ControlID = this.GridControl.ID;
            contextMenu.ID = "RadMenu1";
            contextMenu.Targets.Add(target);
            RadMenuItem item1 = new RadMenuItem("Add");
            RadMenuItem item2 = new RadMenuItem("Edit");
            RadMenuItem item3 = new RadMenuItem("Delete");
            RadMenuItem item4 = new RadMenuItem("Parus");
            contextMenu.Items.Add(item1);
            contextMenu.Items.Add(item2);
            contextMenu.Items.Add(item3);
            contextMenu.Items.Add(item4);
            contextMenu.ItemClick += contextMenu_ItemClick;
            Controls.Add(contextMenu);
            RadGrid1.ClientSettings.ClientEvents.OnRowContextMenu = "function (sender, args) { RowContextMenu(sender, args, $find('" +
                contextMenu.ClientID + "'), $get('" + HiddenField1.ClientID + "')); }";
        }
 
        protected void contextMenu_ItemClick(object sender, RadMenuEventArgs e)
        {
            int rowIndex = int.Parse(HiddenField1.Value);
            switch (e.Item.Text)
            {
                case "Edit":
                    RadGrid1.Items[rowIndex].Edit = true;
                    RadGrid1.Rebind();
                    break;
                case "Add":
                    RadGrid1.MasterTableView.IsItemInserted = true;
                    RadGrid1.Rebind();
                    break;
                case "Delete":
                    RadGrid1.MasterTableView.PerformDelete(RadGrid1.Items[rowIndex]);
                    break;
            }
        }
 
        public RadGrid GridControl
        {
            get
            {
                return this.RadGrid1;
            }
        }
    }
}

Here's JavaScript code that is placed in separate file:

function showMessage()
{
    alert("Hello");
}
 
function RowContextMenu(sender, eventArgs, menu, hiddenField) {
    var evt = eventArgs.get_domEvent();
 
    if (evt.target.tagName == "INPUT" || evt.target.tagName == "A") {
        return;
    }
 
    var index = eventArgs.get_itemIndexHierarchical();
    hiddenField.value = index;
    menu.show(evt);
 
    evt.cancelBubble = true;
    evt.returnValue = false;
 
    if (evt.stopPropagation) {
        evt.stopPropagation();
        evt.preventDefault();
    }
}

My question is how can I get rid of appearing context menu in grid's header?
Tags
Grid
Asked by
Goran
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
Goran
Top achievements
Rank 1
Eyup
Telerik team
Share this question
or