views:

635

answers:

3

I'm presenting information from a DataTable on my page and would like to add some sorting functionality which goes a bit beyond a straight forward column sort. As such I have been trying to place LinkButtons in the HeaderItems of my GridView which postback to functions that change session information before reloading the page.

Clicking my links DOES cause a postback but they don't seem to generate any OnClick events as my OnClick functions don't get executed. I have AutoEventWireup set to true and if I move the links out of the GridView they work fine.

I've got around the problem by creating regular anchors, appending queries to their hrefs and checking for them at page load but I'd prefer C# to be doing the grunt work. Any ideas?

Update: To clarify the IDs of the controls match their OnClick function names.

A: 

Two things to keep in mind when using events on dynamically generated controls in ASP.Net:

  • Firstly, the controls should ideally be created in the Page.Init event handler. This is to ensure that the controls have already been created before the event handling code is ran.
  • Secondly, you must assign the same value to the controls ID property, so that the event handler code knows that that was the control that should handle the event.
samjudson
+2  A: 

You're on the right track but try working with the Command Name/Argument of the LinkButton. Try something like this:

In the HeaderTemplate of the the TemplateField, add a LinkButton and set the CommandName and CommandArgument

<HeaderTemplate> 
    <asp:LinkButton ID="LinkButton1" runat="server" CommandName="sort" CommandArgument="Products" Text="<%# Bind('ProductName")' />
</HeaderTemplate>

Next, set the RowCommand event of the GridView

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "sort")
    {
     //Now sort by e.CommandArgument

    }
}

This way, you have a lot of control of your LinkButtons and you don't need to do much work to keep track of them.

Alison
A: 

You can specify the method to call when the link is clicked.

<HeaderTemplate>
    <asp:LinkButton
        ID="lnkHdr1"
        Text="Hdr1"
        OnCommand="lnkHdr1_OnCommand"
        CommandArgument="Hdr1"
        runat="server"></asp:LinkButton>
</HeaderTemplate>

The code-behind:

protected void lnkHdr1_OnCommand(object sender, CommandEventArgs e)
{
    // e.CommandArgument
}
Eric Z Beard