How to change the Header Text of Gridview after Databound?

允我心安 提交于 2020-01-12 14:41:13

问题


I have a gridview I bound a DataTable with that Gridview Its dynamic so no hardcode Text in desin.

I tried to change it after Databound and in PreRender of gridview but no Success.

Actually there are Underscores('_') in text and I want to Replace it with space.

Below is code

<asp:GridView ID="grdSearchResult" runat="server" AutoGenerateColumns="True" Width="99%" OnPreRender="grdSearchResult_PreRender"
            OnRowCreated="grdSearchResult_OnRowCreated" OnPageIndexChanging="grdSearchResult_PageIndexChanging">
            <HeaderStyle ForeColor="White" BackColor="#215B8D" />
            <AlternatingRowStyle BackColor="#F7F7F7" />
            <RowStyle CssClass="gridtext" HorizontalAlign="Center" />
        </asp:GridView>



protected void grdSearchResult_PreRender(object sender, EventArgs e)
{
    for (int i = 0; i < grdSearchResult.Columns.Count; i++)
    {
        grdSearchResult.Columns[i].HeaderText = grdSearchResult.Columns[i].HeaderText.Replace("_", "");
    }
}

回答1:


Can do this with RowDataBound event of GridView

protected void grdSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
     if (e.Row.RowType == DataControlRowType.Header)
     {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            e.Row.Cells[i].Text = e.Row.Cells[i].Text.Replace("_", " ");
        }
     }
}

and it works fine.




回答2:


You can change the text of the cell rather than the HeaderText property:

        for (int i = 0; i < grdSearchResult.Columns.Count; i++)
        {
            grdSearchResult.HeaderRow.Cells[i].Text = grdSearchResult.HeaderRow.Cells[i].Text.Replace("_", "");
        }

You don't need to do this in PreRender, just after the data has been bound.




回答3:


Set AutoGenerateColumns property of gridview to false and add BoundFields.

<asp:GridView ID="grdEmployee" runat="server" AutoGenerateColumns="false">
<columns>
<asp:BoundField HeaderText="ID" DataField="empNo" />
<asp:BoundField HeaderText="First Name" DataField="fName" />
<asp:BoundField HeaderText="Last Name" DataField="lName" />
</columns>
</asp:GridView>



回答4:


But in OnRowDataBound event the original e.Row.Cell[i].Text is not available for altering.

Eg. in the code below the "headerRow" is always empty.

protected void grdSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
     if (e.Row.RowType == DataControlRowType.Header)
     {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            string headerRow = e.Row.Cells[i].Text;
            e.Row.Cells[i].Text = headerRow.Replace("_", " ");
        }
     }
}


来源:https://stackoverflow.com/questions/3757946/how-to-change-the-header-text-of-gridview-after-databound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!