Friday, April 13, 2012

Changing Gridview Header text Dynamically

Author : Prakash Pradeep Gopu

In this article I will explain how to change gridview header dynamically at runtime using During working in one of my application I got one requirement like change gridview header dynamically whenever we click on some button.
To implement this first design table in your database and give name as UserInformantion.

After completion of table enter some dummy data to bind that one to gridview after that create new website and design your aspx page like this :

<html xmlns="">
<head id="Head1" runat="server">
<title>Change Gridview Header Dynamically at runtime in</title>
<form id="form1" runat="server">
<asp:Button ID="btnChange" Text="Change Header Text" runat="server" onclick="btnChange_Click" />
<asp:GridView ID="gvUserInfo" runat="server">
<HeaderStyle BackColor="Green" Font-Bold="true" ForeColor="White" />

Then include the following name spaces on the C# or Code behind file.

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Then write the following code in the code behind file :

protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)


        protected void BindGridview()
            string connetion = ConfigurationManager.ConnectionStrings["Bloggerconnection"].ToString();
            SqlConnection con = new SqlConnection(connetion);
            SqlCommand cmd = new SqlCommand("select * from UserInformation", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            gvUserInfo.DataSource = ds;

        protected void btnChange_Click(object sender, EventArgs e)
            if (gvUserInfo.Rows.Count > 0)
                gvUserInfo.HeaderRow.Cells[1].Text = "First Name";
                gvUserInfo.HeaderRow.Cells[3].Text = "Destination";
Output :


1 comment:

  1. Its a very simple code for changing the header dynamically at run time. Could you please tell me how do i enable the header to sort in ascending and descending order.