Wednesday, March 17, 2010

How to find control on GridView RowCommand Event?

Here I'm showing how to find a control within a gridview to get some data of that control.
<Columns>
 <asp:TemplateField HeaderText="Team">
    <ItemTemplate>
     <asp:Label ID="lblTeam" runat="server" Text='<%# Eval("TeamName")%>'></asp:Label>
   </ItemTemplate>
 </asp:TemplateField>
</Columns>
<Columns>
 <asp:TemplateField>
    <ItemTemplate>
       <asp:LinkButton ID="lnkEdit" Text="EDIT" runat="server" CssClass="coachEdit"   CommandArgument='<%# Eval("TeamId")%>' CommandName="Redirect"></asp:LinkButton>
   </ItemTemplate>
 </asp:TemplateField>
</Columns>

Here i need the Team Name from the lblTeam and I'm like to get this when I click the Edit link means lnkEdit  so on RowCommand event i have to write this code


GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
 Label lblDate = (Label)row.Cells[0].FindControl("lblDate");
string teamName= lblDate.Text;
int rowindex = row.RowIndex;