2012-11-29 16 views
1

代码隐藏,如何在asp.net中为项目模板标签赋值?

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

保护无效GridView1_RowDataBound(对象发件人,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(); 

     } 
    } 

回答

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"); 
    
+0

嗨alex,e.Row.FindControl(“Label5”);它为我工作... – Sangeetha

+0

太棒了!保持良好的工作 ;) –

1

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

1

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

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