This post will show how can you add a SPMenuField into a SharePoint 2007 SPGridView, generate postbacks and handle them as events. First of all you need to add a reference to Microsoft.SharePoint.dll or if you are building a custom ASPX page as me, add a directive to the library:
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
Asp.Net controls launch postbacks through Javascript so you will need to manually care about them. Insert this Javascript code to help you out in this task:
<script type="text/javascript">
function performPostBack(param) {
__doPostBack("<%= this.UniqueID %>", param);
}
</script>
now you need to build your SharePoint MenuTemplate and add it to your SharePoint's SPGridView.
<SharePoint:MenuTemplate ID="mtEventMenu" runat="server">
<SharePoint:MenuItemTemplate ID="mitDetails" runat="server"
Text="Details" ImageUrl="/_layouts/images/hhelp.gif"
ClientOnClickScript="performPostBack('DETAILS,%Id%');" Title="Details">
</SharePoint:MenuItemTemplate>
<SharePoint:MenuItemTemplate ID="mitDelete" runat="server"
Text="Delete" ImageUrl="/_layouts/images/delete.gif"
ClientOnClickScript="performPostBack('DELETE,%Id%');" Title="Delete">
</SharePoint:MenuItemTemplate>
</SharePoint:MenuTemplate>
<SharePoint:SPGridView ID="spgConfigurationGrid" width="100%"
runat="server" DataKeyNames="Id" AllowPaging="true"
AllowSorting="true" AutoGenerateColumns="false" >
<Columns>
<SharePoint:SPMenuField
HeaderText="Name"
TextFields="Name"
MenuTemplateId="mtEventMenu"
NavigateUrlFields="Id"
NavigateUrlFormat="{0}"
TokenNameAndValueFields="Id=Id"
SortExpression="Id" />
<!-- add code for other columns --> ........
</Columns>
</SharePoint:SPGridView>
If you just need to create a simple MenuItem without rendering a link around your item you should change the SPMenuField's NavigateUrlFormat property from:
NavigateUrlFormat="{0}"
to
NavigateUrlFormat="#"
What's next?
As you can see your MenuItemTemplate will perform a postback by invoking the javascript's funcion called performPostBack when is clicked. We just need to write some code to handler it. In yout code behind apply the IPostBackEventHandler interface and implement the member named RaisePostBackEvent:
public void RaisePostBackEvent(string eventArgument)
{
string[] events = eventArgument.Split(',');
switch (events[0].Trim())
{
case "DELETE":
// DO SOMETHING
break;
case "DETAILS":
// DO SOMETHING ELSE
break;
}
}
As you can see, when a postback is raised, you can intercept the control that causes the event and you can find out if your SPMenuField has been clicked.
As you can see, here's the result: