[英]How to change the Header Text of Gridview after Databound?
我有一個 gridview 我綁定了一個 DataTable 與那個 Gridview 它的動態所以在 desin 中沒有硬編碼文本。
我嘗試在 Databound 和 gridview 的 PreRender 之后更改它,但沒有成功。
實際上文本中有下划線('_'),我想用空格替換它。
下面是代碼
<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("_", "");
}
}
可以用GridView
RowDataBound
事件做到這一點
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("_", " ");
}
}
}
它工作正常。
您可以更改單元格的文本而不是 HeaderText 屬性:
for (int i = 0; i < grdSearchResult.Columns.Count; i++)
{
grdSearchResult.HeaderRow.Cells[i].Text = grdSearchResult.HeaderRow.Cells[i].Text.Replace("_", "");
}
您不需要在 PreRender 中執行此操作,只需在綁定數據之后即可。
將 gridview 的 AutoGenerateColumns 屬性設置為 false 並添加 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>
但是在 OnRowDataBound 事件中,原始的 e.Row.Cell[i].Text 不可用於更改。
例如。 在“headerRow”下面的代碼中始終為空。
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("_", " ");
}
}
}
如果您的標題比其他示例(例如排序按鈕)更復雜,請使用:
protected void gvMain_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow oRow = e.Row;
if (oRow.RowType == DataControlRowType.Header)
{
foreach (TableCell oCell in oRow.Cells)
{
foreach (var oCtl in oCell.Controls) {
if(oCtl.GetType() == typeof(System.Web.UI.WebControls.Label))
{
Label oLBL = (Label)oCtl;
oLBL.Text = oLBL.Text.Replace("_", "");
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.