Gridview, change dynamically headerText

21k views Asked by At

I have a gridview and I want to change dynamically the name of header. It is possible ? I have this code :

OracleCommand cmdReqStockComp = new OracleCommand(reqStockCompTotal);
cmdReqStockComp.Connection = oConnexion;
OracleDataReader readerReqStockComp = cmdReqStockComp.ExecuteReader();

// ************** ETAPE 2 : On remplit la GridView ************ //

// On lie le résultat de la requête à la GridView
gvReportingStockComp.DataSource = readerReqStockComp;
gvReportingStockComp.DataBind();

And this aspx code :

<asp:GridView ID="gvReportingStockComp" runat="server" AutoGenerateColumns="false" Visible="false">

            <Columns>

                <asp:BoundField DataField="cod_wo" HeaderText="N° OF" />
                <asp:BoundField DataField="composant" HeaderText="Composant" />
                <asp:BoundField DataField="BESOIN" HeaderText="Besoin/OF" />
                <asp:BoundField DataField="BESOIN_T" HeaderText="Besoin total" />
                <asp:BoundField DataField="stock_dispo" HeaderText="Stock dispo" />
                <asp:BoundField DataField="QTE_RESTANTE" HeaderText="Qte restante" />

            </Columns>

        </asp:GridView>

Thanks :)

4

There are 4 answers

1
Andrei On

On a very basic level you can do just

gvReportingStockComp.Columns[0].HeaderText = "New Header for First Column";
0
Akshay On

Better to use this

if (e.Row.RowType == DataControlRowType.Header)
{
       e.Row.Cells[0].Text = "HeaderText";
}

instead of

gvReportingStockComp.Columns[0].HeaderText = "New Header for First Column";

this ^ did not work for me.

0
Jon Reedholm On

Had to use Preload event to update headertext for sorted columns. My code gets UIlabels from DB in UpdatePage call and then GetUIText gets one label. Set HeaderText in HTML to number of case for updating text.

Protected Sub Page_preLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreLoad
    If UpdatePage(Page.Controls, UIsetBase, "122000," + BldCommonScreen) = False Then
        SetMasterErrMsg(Master, "blderrmsg", Session("ErrorMsg"))
    End If

    For Each Col In OpenTestGridView.Columns
        Dim ht As String = Col.HeaderText
        Select Case ht
            Case "1"
                Col.HeaderText = GetUILabel("114100")
            Case "2"
                Col.HeaderText = GetUILabel("114101")
            Case "3"
                Col.HeaderText = GetUILabel("114102")
            Case "4"
                Col.HeaderText = GetUILabel("114103")
            Case "5"
                Col.HeaderText = GetUILabel("114104")
            Case "6"
                Col.HeaderText = GetUILabel("114105")
            Case "7"
                Col.HeaderText = GetUILabel("114008")
            Case "8"
                Col.HeaderText = GetUILabel("123158")
        End Select
    Next
End Sub
0
Jonatas On

To change header text after data-binding:

gridview.HeaderRow.Cells[0].Text = "new value";