2012-07-31

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.

ASPX

<%@ 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="
http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" OnRowCommand="List_RowCommand">
        <Columns>
            <asp:TemplateField HeaderText="Status">
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Action">
                <ItemTemplate>
                    <asp:LinkButton CommandName="Activate" ID="lnkActivate"
                        runat="server" Text="testlink"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>

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();
            dt.Rows.Add(dr);

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        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()