Link to home
Start Free TrialLog in
Avatar of WNottsC
WNottsCFlag for Afghanistan

asked on

Determine Row Index - Template Control Buttons in Gridview

I have gridview control which had rows containing 2 button colums which was working ok. I was using this syntax to determine the row & what action to take in the code behind...

     Private Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand

        Dim index As Integer = Convert.ToInt32(e.CommandArgument)
        Dim row As GridViewRow = Me.GridView1.Rows(index)
        Me.GridView1.SelectedIndex = index

        If e.CommandName = "Exclude" Then
               etc....

However I have converted the buttons to template controls & now Im stumped because the RowCommand event doesnt fire anymore & I cant see how to determine the row index in the buttons click event

How do I get the row index for button clicked in a template control?
Avatar of TSmooth
TSmooth

Make sure that your templated buttons have a CommandName attribute set which should force the RowCommand event to fire. To get the index of the row in which the clicked button was pressed, you need to set the CommandArgument attribute of your buttons in the RowDataBound event handler of your grid view.

If your template column looks something like this:
<asp:TemplateField>
  <ItemTemplate>
    <asp:Button id="btnRowButton" runat="server" CommandName="Exclude" Text="Exclude" />
  </ItemTemplate>
</asp:TemplateField>

Then in your RowDataBound Event handler do the following:
If e.Row.RowType = DataControlRowType.DataRow Then
  Dim btnRowButton As Button = DirectCast(e.Row.FindControl("btnRowButton"), Button)
  btnRowButton.CommandArgument = e.Row.RowIndex
End If
Avatar of Bob Learned
How are the controls defined in the TemplateField?  Did you define any event handlers in the HTML designer?

Bob
LinkButton button = (LinkButton)sender;
        GridViewRow grdRow = (GridViewRow)button.Parent.Parent;

Try some thing like this
Avatar of WNottsC

ASKER

I havent added any code in html designer, do I need to?  I did 'convert to template' from with the grid designer then edited the template & added a button.

The CommandName is set but RowCommand does not fire.

Ive added the bit to save the rowindex in the commandargument & that seems to work ok but like I say the RowCommand is not firing so cant do much with it :(
If you have a TemplateField, then the controls are defined in the HTML designer.  That was what 'Convert to Template' did for you.

Bob
ASKER CERTIFIED SOLUTION
Avatar of TSmooth
TSmooth

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of WNottsC

ASKER

Thanks

Deleteing the buttons & recreting them fixed the event together with the RowDataBound event works ok now.