Categories
Asp, Asp.net

Change Gridview Header Text Dynamically At Runtime in Asp.Net

Change Gridview Header Text Dynamically At Runtime in Asp.Net

In this post i will let you know, that how can you change Gridview header text dynamically  in Asp.Net at runtime.Here i am using a SQL Server database for backend, Table1 is table on which i am working on.

Table1

Column Name Data Type Allow Nulls
Autoincrementno int No
ProjectID Varchar(20) No
Exclude Varchar(10) No

Now insert some test data into Table1.

Design View:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="datagrid.aspx.cs" Inherits="datagrid" %> <!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div> <asp:GridView ID="GridView1" runat="server"> </asp:GridView><br/>
<asp:Button ID="Button1" runat="server" Text="Changing Header Text" onclick="Button1_Click" />
</div>
</form>
</body>
</html>


Code:-

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data; using System.Configuration;
public partial class datagrid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
SqlConnection ocon = new SqlConnection(strcon); ocon.Open();
SqlCommand cmd = new SqlCommand("select autoincrementno,projectis,exclude from table1", ocon); SqlDataAdapter da= new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (GridView1.Rows.Count > 0)
{
GridView1.HeaderRow.Cells[1].Text = "Project";
GridView1.HeaderRow.Cells[2].Text = "Status";
} } }


In this we are changing Gridview1 header ProjectID to Project and Exclude to Status on button click event.

Enjoy:)