0

I have a ASP:grid which has a link button, i need to some how reference that on the code behind when its clicked but im struggling on the syntax

Heres my ASP:Grid i need to execute code in the code behind when that link button 'Re-Take' is pressed and also be able to know what row it was clicked on as i will need to reference the users emails and name and then send an email with the relevant information....

<asp:GridView ID="GrdViewUsers" runat="server" AutoGenerateColumns="false" GridLines="None"
                    EnableViewState="false" class="tablesorter">
    <AlternatingRowStyle></AlternatingRowStyle>
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton Text="Re-Take" runat="server" ID="Edit" CommandName="Edit"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Full Name">
            <ItemTemplate>
                <asp:HyperLink ID="HyperFullName" CssClass="gvItem" runat="server" NavigateUrl='<%#Eval("UserID","/ExamPaper.aspx?uid={0}") %>'
                    Text='<%# DataBinder.Eval(Container,"DataItem.FullName") %>'></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Email">
            <ItemTemplate>
                <asp:Label ID="lblSurname" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Email") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Exam Taken">
            <ItemTemplate>
                <asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ExamTaken") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Date Taken">
            <ItemTemplate>
                <asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.DateTaken") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Exam Total">
            <ItemTemplate>
                <asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ExamTotal") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

If someone can help me with a snippet i would highly appreciate it

Andrei
  • 55,890
  • 9
  • 87
  • 108
Code Ratchet
  • 5,758
  • 18
  • 77
  • 141

4 Answers4

1

You could approach this slightly different. You see, when a control is placed inside a gridview, any event raised from that control raises also the RowCommand on the GridView.

To get what you want you could then add both CommandName and CommandArgument to your LinkButton and then catch it in the GridView's RowCommand.

<asp:LinkButton id="LinkButton1" runat="server" commandName="LinkButtonClicked" commandArgument='Eval("myObjectID")' />

where myObjectID is the name of the ID column of your object you bind the grid to.

Then

void GridView1_RowCommand( object sender, GridViewCommandEventArgs e )
{
    if ( e.CommandName == "LinkButtonClicked" )
    {
        string id = e.CommandArgument; // this is the ID of the clicked item
    }
}

see: ASP.net GridView: get LinkItem's row

Community
  • 1
  • 1
MUG4N
  • 19,377
  • 11
  • 56
  • 83
0

FindControl should work in this case.

protected void GrdViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        HyperLink myHyperLink = e.Row.FindControl("Edit") as HyperLink;
    }
}
sarwar026
  • 3,821
  • 3
  • 26
  • 37
  • Hi thanks for the snippet, is there not a click event similar to how you would do a normal click event for a button? – Code Ratchet May 05 '12 at 13:58
0

Suppose the grid has linkbutton on which we want to get row index

 <asp:LinkButton ID="lnkbtnAdd " runat="server" CommandName="cmdAdd" ImageUrl="~/Images/add.gif" ></asp:LinkButton>

In code behind, In OnRowCreated event we attach row number of grid to each button of row to get it back when it is clicked in RowCommand event

    protected void gvListing_RowCreated(object sender, GridViewRowEventArgs e)
    {           
        if (e.Row.RowType == DataControlRowType.DataRow)
        {                
          System.Web.UI.WebControls.LinkButton lnkbtnAdd = new System.Web.UI.WebControls.LinkButton();    
                lnkbtnAdd = (System.Web.UI.WebControls.LinkButton)e.Row.FindControl("lnkbtnAdd");                    
                if (lnkbtnAdd != null)
                    lnkbtnAdd .CommandArgument = e.Row.RowIndex.ToString();
         }          
    }

In RowCommand event we will get back the current row index and set the selected index of the grid

protected void gvListing_RowCommand(object sender, GridViewCommandEventArgs e)
{      
   if (e.CommandName.ToString() == "cmdAdd")
   { 
       int RowIndex = int.Parse(e.CommandArgument.ToString());// Current row

   }
}
Adil
  • 146,340
  • 25
  • 209
  • 204
0

First: You have repeating ID's in your TemplateFields like lblUsername what is not allowed since it's the same NamingContainer.

You can pass the RowIndex as CommandArgument to RowCommand:

on aspx:

<asp:TemplateField>
    <ItemTemplate>
        <asp:LinkButton 
           Text="Re-Take" 
           runat="server" 
           ID="Edit" 
           CommandName="Edit"
           CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
        </asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField>

Handle the GridView's RowCommand:

  void GrdViewUsers_RowCommand(Object sender, GridViewCommandEventArgs e)
  {
    if(e.CommandName=="Edit")
    {
        int index = Convert.ToInt32(e.CommandArgument);      
        GridViewRow row = GrdViewUsers.Rows[index];
        // now you can get all of your controls like:
        Label lblSurname = (Label)row.FindControl("lblSurname");
        String email = lblSurname.Text // you noticed that DataItem.Email is bound to lblSurname?
    }
  }  
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • iv done the above but when i click on the link button the page just flashes and doesnt go in to the grdviewuser_rowcommand code behind? – Code Ratchet May 05 '12 at 15:53
  • Iv add onrowcommand="GrdViewUsers_RowCommand in the asp:grid i then added CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"> do i need to change anything in that? as im not 100% sure, i then added the GridViews RowCommand snippet in my code behind, when i run and put a break point in the code nothing is hit the page just refreshes........ – Code Ratchet May 05 '12 at 16:15
  • @ScottAtkinson: It should work if you've added the rowcommand handler on the gridview markup(as you've said above). Are you databinding the GridView in page load on postbacks? You should do that only if `!Page.IsPostback`. – Tim Schmelter May 05 '12 at 18:10
  • when the page loads for the first time it gets binded, but the code you have given me when i put a break point inside that well on the if(e.commandname == "Edit") it doesnt hit it this is what i have in my page load protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BuildGrids(); } } the builddgrids is where i databind the grdViewUSers but again stepping through the page load event it goes in and then thats it? – Code Ratchet May 05 '12 at 18:33
  • @Scott: No, nothing wrong as far as I can tell. I don't know why RowCommand isn't fired. Does it work if you handle the LinkButton's click event instead? You get the GridViewRow reference there via `var row = (GridViewRow)((LinkButton)sender).NamingContainer;` – Tim Schmelter May 05 '12 at 21:38
  • Hm, ill have a play around with it and see whats actually going wrong – Code Ratchet May 06 '12 at 10:57