4

I have a gridview with 2 columns. I want to learn coding behind and do NOT want to do this in the aspx file. How do I set the header text for my columns dynamically? At what point do I do so? After the adapter has filled the gridview with data? Right now, I have the header text but it is exactly the same as the datafield name which is last_name and I want to see Last Name in the header field instead. I've tried

GridView1.Columns[0].HeaderText = "Last Name";

but wherever I tried to put it, the compiler complains about index out of range.

Thanks.

aspx code for the gridview:

    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
                BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"
                Width="728px" CellPadding="4" ForeColor="Black" GridLines="Vertical" OnPageIndexChanging="GridView1_PageIndexChanging"
                OnSorting="GridView1_Sorting" PageSize="14" OnRowDataBound="GridView1_RowDataBound">
                <AlternatingRowStyle BackColor="White" />
                <FooterStyle BackColor="#CCCC99" />
                <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
                <RowStyle BackColor="#F7F7DE" />
                <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
                <SortedAscendingCellStyle BackColor="#FBFBF2" />
                <SortedAscendingHeaderStyle BackColor="#848384" />
                <SortedDescendingCellStyle BackColor="#EAEAD3" />
                <SortedDescendingHeaderStyle BackColor="#575357" />
                <PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last"
                    PageButtonCount="5" Position="Bottom" />
            </asp:GridView>
user776676
  • 4,265
  • 13
  • 58
  • 77

4 Answers4

14

Try putting it in the GridView1.RowDataBound handler. Evaluate e.Row.RowType to determine if it is a header row, then then replace the HeaderText.

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header) {
        GridView1.Columns[0].HeaderText = "Last Name";

    }
}

If you are dynamically creating the columns and using sorting, however, you will need to approach it this way to prevent the incidental conversion of the link to sort into plain text:

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header) {
        LinkButton HLink = (LinkButton)e.Row.Cells[0].Controls[0];
        HLink.Text = "Last Name";
    }
}

With either, add this attribute to your Gridview in the ASPX:

OnRowDataBound="GridView1_RowDataBound"
Joe
  • 436
  • 5
  • 15
  • Would you mind giving a bit more information about this? I'm very curious about the answer as well. Maybe a bit of code? – Jeremy Jun 10 '11 at 01:17
  • Thanks so much, Joe. But after I managed to change the header text: I lost the sorting ability by clicking on the header of the column. If you don't have the answer right away, I can post a separate question. Thanks again. – user776676 Jun 10 '11 at 02:15
  • See the updated sample. You were actually better off using the HeaderText attribute than what I originally suggested. – Joe Jun 10 '11 at 02:52
  • Actually, Joe, the original worked. But the updated code didn't. Please change the code back to make it the correct answer. Thanks. – user776676 Jun 10 '11 at 03:39
  • The second method definitely works in my test (rename and sorting), so there's something else in play. What error message are you getting, still "index out of range"? Could you post the code for the GridView? – Joe Jun 10 '11 at 14:05
  • Joe: Yes, I got the same index out of range error with the latter method. The code is exactly the same as what you posted. Identical RowDataBound handling. The one with Row.Cells works, the one with GridView1.Columns does not. It would be wonderful if I can make GridView1 version work because it doesn't interfere with sorting. – user776676 Jun 10 '11 at 14:25
  • What I'm looking for is the code for the gridview in the aspx page. If I have that, I may be able to help. – Joe Jun 10 '11 at 14:28
  • The aspx code is added to the original question as I don't know how to add it properly to the comment. To be clearer, the problem with sorting was that before: the header text was like a hyperlink; I could click on it and it sorts. After dynamically change the header text, the header is like plain text; clicking doesn't do anything. – user776676 Jun 10 '11 at 14:52
  • Cool, it was due to the fact that you were generating the columns dynamically, and thereby HeaderText is not available. See the second code sample. – Joe Jun 10 '11 at 15:44
  • @Joe : You are absolutely amazing! Thanks so much for helping me. – user776676 Jun 10 '11 at 17:00
  • Joe, you can use `Gridview.HeaderRow.Cells[x]` to access the header row directly, without having to inspect each row to see if it is a header row. – Bede Amarasekara Oct 29 '13 at 12:31
2

Add to Page_Load, but

GridView1.Columns[0].HeaderText = "Last Name"; 

wouldn't work as it would complain that the column count is 0, hence do this:

protected void grdProd_Load(object sender, EventArgs e)
{
    grdProd.HeaderRow.Cells[0].Text = "Item";
    grdProd.HeaderRow.Cells[1].Text = "Category";
}
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
1

I don't think you want to bind text for your header during every row data bind event (1 time for each row) in your Grid!

Just hook on to the Loaded event for the page and then bind the text there like you had it.

 protected void Page_Load(object sender, EventArgs e)
 {
    GridView1.Columns[0].HeaderText = "Last Name";
 }
Brian Webster
  • 30,033
  • 48
  • 152
  • 225
SnowyNomad
  • 11
  • 2
0
     <%@ Page Language="C#" AutoEventWireup="true" CodeFile="grdvw8.aspx.cs" Inherits="grdvw8" %>



    <!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">

    <div>

    first header name change To<asp:TextBox ID="txt1" runat="server"></asp:TextBox>

    <br />

    Second header name change To<asp:TextBox ID="txt2" runat="server"></asp:TextBox>

    <br />

    <asp:Button ID="btnChange" Text="Change Header Text" runat="server" onclick="btnChange_Click" />

    <asp:GridView ID="grdvw" runat="server">

    <HeaderStyle Font-Bold="true" ForeColor="Brown" />

    </asp:GridView>

    </div>

    </form>

    </body>

    </html>


/ASPX.CS PAGE/

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;



public partial class grdvw8 : System.Web.UI.Page

{

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["code"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)

    {

        Bind();

    }



    protected void Bind()

   {

         con.Open();

          SqlCommand cmd=new SqlCommand("select * from gridview",con);

          SqlDataAdapter da=new SqlDataAdapter(cmd);

          DataSet ds=new DataSet();

          da.Fill(ds);

        grdvw.DataSource = ds;

         grdvw.DataBind();



   }



    protected void btnChange_Click(object sender, EventArgs e)

    {

        if (grdvw.Rows.Count > 0)

        {

            grdvw.HeaderRow.Cells[0].Text = txt1.Text;

            grdvw.HeaderRow.Cells[1].Text = txt2.Text;

        }

    }



}
Code
  • 679
  • 5
  • 9