如何在Gridview页脚模板中设置标签的值?

时间:2014-08-07 16:13:56

标签: c# asp.net gridview webforms

我在gridview上有一些标签,我试图在页面加载时将文本设置为。我修复了"对象引用错误"但是我还没弄清楚如何动态设置标签文本。这是我试过的:

protected string AutoDate, Website;

protected void Page_Load(object sender, EventArgs e)
{
    BindData();
    pnlMainGrid.Visible = true;
    DateTime dtMyDate = DateTime.Now;
    AutoDate = Convert.ToString(dtMyDate);
    Website = "MySite";
    Label lblCreateDate = ((Label)gvMainView.FooterRow.FindControl("lblCreateDate"));
    lblCreateDate.Text = AutoDate;
    Label lblWebsite = ((Label)gvMainView.FooterRow.FindControl("lblWebsite"));
    lblWebsite.Text = Website;
}

被修改

我不再获得"对象参考"但是我仍然无法动态设置标签的文本。

1 个答案:

答案 0 :(得分:0)

正确的方法是在将网格与数据绑定后,在Prerender事件中更改标签文本,如下所示:

protected void Page_PreRender(object sender, EventArgs e)
{
      Label lblCreateDate = ((Label)gvMainView.FooterRow.FindControl("lblCreateDate")).Text;
    lblCreateDate.Text = AutoDate;
    Label lblWebsite = ((Label)gvMainView.FooterRow.FindControl("lblWebsite")).Text;
    lblWebsite.Text = Website;
}

prerender是您应该在将网格项呈现给用户之前始终操作网格项的地方,否则您将不得不重新加载。

相关问题