如何在asp.net中的项目模板中分配值?

问题描述 投票:1回答:3

代码隐藏,

我得到低于错误对象引用未设置为对象的实例。

protected void GridView1_RowDataBound(object sender,GridViewRowEventArgs e){

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

          string  a = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "item_id")) ;
          string b = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "order_id"));
            Label lbl = (Label)GridView1.FindControl("Label5");

                int sum = int.Parse(a) + int.Parse(b);
                lbl.Text += sum.ToString();

        }
    }
gridview
3个回答
1
投票

根据你的Label5控件的位置,应该有两种可能性:

  1. 如果标签被添加到Gridview1.Controls集合中,那么您应该能够通过以下方法访问它: void GridView1_PreRender(object sender, EventArgs e) { Label lbl = (Label)GridView1.FindControl("Label5"); }
  2. 如果为每行添加标签,例如: void GridView1_RowCreated(object sender, GridViewRowEventArgs e) { var label = new Label(); label.ID = "Label5"; label.Text = "label"; var cell = new TableCell(); cell.Controls.Add(label); e.Row.Controls.Add(cell); } 为了在你的GridView1_RowDataBound方法中找到标签,你应该使用: e.Row.FindControl("Label5");

1
投票

Label lbl = (Label)GridView1.FindControl("Label5");在OnDataBound Event中写这个。


1
投票

确保您的网格项标签ID与FindControl ID后面的代码相同。

foreach (GridViewRow row in gv_Name.Rows)                        {
{
 Label name = (Label)row.FindControl("lblitemNameId");
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.