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;

12 comments:

  1. good work dear.... thanks

    ReplyDelete
  2. it great to hear some comments.
    thank you guys..

    ReplyDelete
  3. You made my evening, thanks Bishnu

    ReplyDelete
  4. Replies
    1. if (e.CommandName == "select")
      {
      GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
      ImageButton img = (ImageButton)row.Cells[0].FindControl("ImageButton3");
      String url1 = img.ImageUrl.ToString();
      Image1.ImageUrl = url1;

      }

      Delete
    2. ImageButton or LinkButton what ever you use for which the RowCommand event get fired please use that control for type cast the e.CommandSource
      Like jatashri use ImageButton so she use like this

      GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);

      Delete