更改GridView中列的标题文本

我有一个GridView,我使用c#代码以编程方式绑定。 问题是,列直接从数据库获取其标题文本,这在网站上呈现时看起来很奇怪。 所以基本上,我想修改列标题文本,但编程方式。 我已经尝试了以下,

testGV.Columns[0].HeaderText = "Date"; 

 this.testGV.Columns[0].HeaderText = "Date"; 

似乎没有给我正确的结果。

您应该在GridView的RowDataBound事件中执行此操作,该事件在数据绑定为每个GridViewRow触发。

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { e.Row.Cells[0].Text = "Date"; } } 

或者您可以将AutogenerateColumns设置为false并在aspx上以声明方式添加列:

      

我觉得这个有效:

  testGV.HeaderRow.Cells[0].Text="Date" 

您可以使用gridview的datarow bound事件来完成。 尝试以下代码示例:

 protected void grv_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { e.Row.Cells[0].Text = "TiTle"; } } 

有关行数据绑定事件研究Thsi的更多详细信息….

在您的asp.net页面上添加gridview

   

在c#类中创建一个名为GridView1_RowDataBound的方法protected void方法

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { e.Row.Cells[0].Text = "HeaderText"; } } 

一切都应该工作正常。

最好从gridview中找到单元格而不是静态/修复索引,这样每当你在gridview上添加/删除任何列时都不会产生任何问题。

ASPX:

      

CS:

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { for (int i = 0; i < e.Row.Cells.Count; i++) { if (string.Compare(e.Row.Cells[i].Text, "Date", true) == 0) { e.Row.Cells[i].Text = "Created Date"; } } } }