2011-06-17 85 views
2

我有一个GridView,而我试图让TextView的一个标签的文本价值访问GridView的标签字段,其中的代码是:从代码隐藏

<asp:TemplateField HeaderText="someText" SortExpression="someExpression"> 
    <ItemTemplate> 
     <asp:Label ID="someLabel" runat="server" Text='<%# Bind("someField") %>'></asp:Label> 
    </ItemTemplate> 
</asp:TemplateField> 

我希望能够到在我的代码隐藏文件中将selectedRow中“someLabel”的文本值作为字符串获取。

回答

1
Label someLabel = selectedRow.FindControl("someLabel") as Label; 

编辑:

private static Control FindControlRecursive(Control parent, string id) 
    { 
     if (parent.ID== id) 
     { 
      return parent; 
     } 

     return (from Control ctl in parent.Controls select FindControlRecursive(ctl, id)) 
      .FirstOrDefault(objCtl => objCtl != null); 
    } 

Label someLabel = FindControlRecursive(GridView.SelectedRow, "someLabel") as Label; 

编辑2:

private void imageButton_Click(object sender, EventArgs e) 
{ 
    Label someLabel = (sender as Control).Parent.FindControl("someLabel") as Label; 
} 
+0

这是我一直想:'标签tempLabel = GridView.SelectedRow.FindControl (“someLabel”)作为标签;',但由于某种原因,这是行不通的。任何想法为什么? –

+0

@Jordan和? tempLabel为空? –

+0

我收到nullreferenceexception –