Author : Prakash Pradeep Gopu
In this article I will explain how to change gridview header dynamically at runtime using asp.net. 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 :
Then include the following name spaces on the C# or Code behind file.
Then write the following code in the code behind file :
In this article I will explain how to change gridview header dynamically at runtime using asp.net. 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="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Change Gridview Header Dynamically at runtime in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<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" />
</asp:GridView>
</div>
</form>
</body>
</html>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)
{
BindGridview();
}
}
protected void BindGridview()
{
string connetion = ConfigurationManager.ConnectionStrings["Bloggerconnection"].ToString();
SqlConnection con = new SqlConnection(connetion);
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
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 :
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.
ReplyDeleteThanks,
Sam.