How to change label text of a particular row in GridView on click of a button next to it

Following example code demonstrates how to access another control in the same row as the clicked button, and change it’s behavior.


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
<head id="Head1" runat="server">
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" OnRowCommand="List_RowCommand">
            <asp:TemplateField HeaderText="Status">
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            <asp:TemplateField HeaderText="Action">
                    <asp:LinkButton CommandName="Activate" ID="lnkActivate"
                        runat="server" Text="testlink"></asp:LinkButton>

Here, I’m going to change the text of Label1 when the testlink button Clicked. Following is the code behind (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Data;

namespace WebApplication1
    public partial class WebForm2 : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("column1");

            DataRow dr = dt.NewRow();

            GridView1.DataSource = dt;

        protected void List_RowCommand(object sender, GridViewCommandEventArgs e)
            GridViewRow clickedRow = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;
            Label lblID = (Label)clickedRow.FindControl("Label1");
            lblID.Text = "Some text here";

Now when the user press the link button, text of the Label which is associated in the same row will change to “Some text here”. In this example, I’m having only a one row.

1 comment:

Chinthana said...

Nice to see you macho as a sri lankan .net blogger.
another easy way is there ,
we can link take button click itself then in side the
click event
LinkButton lnkBtn = sender as LinkButton;
GridViewRow gr = (GridViewRow)lnkBtn.NamingContainer;
then gr.findContorl()