我有一个aspx
页面(比如说MyPage.aspx
),其中一部分具有以下结构-
<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
文件中的元素,并且元素也会被渲染(在浏览器中可见),但在代码隐藏文件中,我在所有 3 个元素中都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
Dim button As Button = CType(DataList1.Items(3).FindControl("Button1"),Button)
button.BackColor = Color.Green