动态获得控件名(在带有master page结构下)

stevenhzhang 2010-03-08 11:51:01
我现在主代码是这样


<%@ Page Language="VB" MasterPageFile="~/Admin/MasterPage.master" AutoEventWireup="false" CodeFile="Page1.aspx.vb" Inherits="Page1" title="Page 1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Label ID="Label1" runat="server" />
<asp:Label ID="Label2" runat="server" />
<asp:Label ID="Label3" runat="server" />
<asp:Label ID="Label4" runat="server" />
</asp:Content>


后台代码


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For i = 1 To 3
CType(Me.FindControl("Label" & CStr(i)), Label).Text = i
Next
End Sub


但是在运行的时候找不到Label1, Label2

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

但是
...全文
116 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
随风落梦 2010-03-09
  • 打赏
  • 举报
回复
由于是母板页,所以会不会Label1这样出现啊?你运行页面后查看下原代码,看看Id变啥了
tzs2304 2010-03-09
  • 打赏
  • 举报
回复
阿非 2010-03-09
  • 打赏
  • 举报
回复
使用 TryCast 代替 CType
stevenhzhang 2010-03-09
  • 打赏
  • 举报
回复
自己解决了。

方法一:直接写


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For i = 1 To 3
CType(Me.Master.FindControl("ContentPlaceHolder1").FindControl("Label" & CStr(i)), Label).Text = i
Next
End Sub


方法二:在外面套了一个Panel


<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Panel ID="PagePanel" runat="server">
<asp:Label ID="Label1" runat="server" />
<asp:Label ID="Label2" runat="server" />
<asp:Label ID="Label3" runat="server" />
<asp:Label ID="Label4" runat="server" />
</asp:Panel>
</asp:Content>

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For i = 1 To 3
CType(PagePanel.FindControl("Label" & CStr(i)), Label).Text = i
Next
End Sub

62,243

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧