【问题标题】:How to assign value inside the item template lable in asp.net?如何在asp.net中的项目模板标签内赋值?
【发布时间】:2017-12-30 18:54:29
【问题描述】:

代码隐藏,

我遇到以下错误 你调用的对象是空的。

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


    【解决方案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");
      

    【讨论】:

      【解决方案2】:

      Label lbl = (Label)GridView1.FindControl("Label5");在 OnDataBound 事件中写入。

      【讨论】:

        【解决方案3】:

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

        foreach (GridViewRow row in gv_Name.Rows)                        {
        {
         Label name = (Label)row.FindControl("lblitemNameId");
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-02-16
          • 1970-01-01
          • 1970-01-01
          • 2014-07-25
          • 2022-11-25
          • 2019-06-05
          • 1970-01-01
          • 2010-09-20
          相关资源
          最近更新 更多