获得“无”(或C#“空”)在器WebControls代码隐藏在ASP.Net Web窗体文件
问题描述:
我有一个aspx
页面(比如MyPage.aspx
),其中它的一部分具有以下结构 -获得“无”(或C#“空”)在器WebControls代码隐藏在ASP.Net Web窗体文件
<asp:DataList ...>
<ItemTemplate>
...
<asp:Panel ID="panel" runat="server" ...>
<asp:Button ID="button1" runat="server" ...>
<asp:Button ID="button2" runat="server" ...>
</asp:Panel>
</ItemTemplate>
</asp:DataList>
我将asp:Panel
元素和asp:Button
手动添加到它手动(写在物理上)到我作为一个项目的一部分得到的页面。我在MyPage
类也添加了这些控件的定义到MyPage.aspx.vb
-
Protected WithEvents panel As System.Web.UI.WebControls.Panel
Protected WithEvents button1 As System.Web.UI.WebControls.Button
Protected WithEvents button2 As System.Web.UI.WebControls.Button
现在,我能够访问元素在vb
文件和元素越来越呈现(在浏览器中查看)太多,但在代码 - 在后面的文件中,我获得了Nothing
,因此我在尝试访问其属性时得到了NullReferenceException
。 (没有MyPage.aspx.designer.vb
文件)
我无法弄清楚为什么。请帮忙。
感谢。
答
正如Michael Liu在他的评论中指出的那样,这些按钮并不存在于DataList范围之外。
如果你想访问这些按钮,你必须使用其他方法,如OnItemDataBound
事件。
<asp:DataList ID="DataList1" runat="server" OnItemDataBound="DataList1_ItemDataBound">
代码背后
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
//find the button in the datalist item object and cast it back to one
Button button = e.Item.FindControl("Button1") as Button;
//you can now access it's properties
button.BackColor = Color.Red;
}
VB
Protected Sub DataList1_ItemDataBound(ByVal sender As Object, ByVal e As DataListItemEventArgs)
'find the button in the datalist item object and cast it back to one
Dim button As Button = CType(e.Item.FindControl("Button1"),Button)
'you can now access it's properties
button.BackColor = Color.Red
End Sub
或项指数直接访问它数据绑定
Button button = DataList1.Items[3].FindControl("Button1") as Button;
button.BackColor = Color.Green;
VB
0后Dim button As Button = CType(DataList1.Items(3).FindControl("Button1"),Button)
button.BackColor = Color.Green
这些控件引用为null,因为控件位于一个''内部,并且有充分的理由:DataList将多次实例化面板和按钮,每次在数据源中每个项目一次,以便哪些控件你的参考资料是指什么? –