简体   繁体   中英

Change Header Text in Column of Gridview pulling from Database

Hi I am wondering how I can change the header text of my column in my Gridview when I am pulling from a Database to build my Gridview.

Here is how I am building the GridView.

    SqlConnection Conn = new SqlConnection("REMOVED");
    SqlDataReader rdr = null;
    string commandString = "SELECT OrderNumber, CreatedDate, CreatedBy, CustomerID, Store_Number, Package FROM dbo.Orderheader";

    try
    {
        Conn.Open();
        SqlCommand Cmd = new SqlCommand(commandString, Conn);
        rdr = Cmd.ExecuteReader();

        GridView1.DataSource = rdr;
        GridView1.DataBind();
    }
    catch (Exception ex)
    {
        // Log error
    }
    finally
    {
        if (rdr != null)
        {
            rdr.Close();
        }
        if (Conn != null)
        {
            Conn.Close();
        }
    }


}

Get the header row object in databound event and change the desired name,

void GridView1_DataBound(Object sender, EventArgs e)
  {

    // Get the header row.
    GridViewRow headerRow = GridView1.HeaderRow;
    headerRow.Cells[0].Text = "Order";
    headerRow.Cells[1].Text = "Date";
  } 

OR

Set AutoGenerateColumns to False and use Column bound fields ,

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<columns>

<asp:BoundField HeaderText="Order" DataField="OrderNumber" />
<asp:BoundField HeaderText="Date" DataField="CreatedDate" />

</columns>
</asp:GridView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM