我收到上面的错误,我现在真的陷入困境,这是一个简单的表单,我试图在单击按钮时动态添加控件。 我对代码的评论很高兴我收到错误“pnltxtProductDescription.Controls.Add(txt)'这就是我在哪里得到错误”
我的ASP页面
<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Pages/master-pages/main.Master" CodeBehind="quotation-new.aspx.vb" Inherits="iconHub.quotation_new1" %>
<title>New Quotation | iconHub</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<div id="wrapper" class="wrapper">
<!-- MAIN CONTENT WRAPPER -->
<div id="main-content-wrapper" class="content-wrapper ">
<div class="main-content">
<div class="col-md-12" style="padding-bottom: 15px;">
<div class="row">
<table class="table table-bordered">
<thead>
<tr>
<th class="col-md-1">#</th>
<th class="col-md-2">Item</th>
<th class="col-md-4">Description</th>
<th class="col-md-2">Unit Cost</th>
<th class="col-md-1">Quantity</th>
<th class="col-md-2">Line Total</th>
</tr>
</thead>
</table>
</div>
<div class="col-md-4">
<!--Left Column-->
<div class="form-group">
<input type="text" class="form-control" name="txtProductDescription" runat="server" id="txtProductDescription">
</div>
</div>
</div>
<div class="row">
<asp:Panel ID="pnltxtProductDescription" runat="server">
</asp:Panel>
</div>
</div>
<div class="col-md-12 pull-right" style="padding-bottom: 15px;">
<div class="row">
<asp:Button id="cmdAddLine" CssClass="btn btn-default nextBtn btn-sm pull-right" runat="server" onclick="AddTextBox" Text="Add Line" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
我的幕后代码
Public Class quotation_new1 Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub AddTextBox(sender As Object, e As EventArgs)
Dim index As Integer
'Description
index = pnltxtProductDescription.Controls.OfType(Of TextBox)().ToList().Count + 1
CreatetxtProductDescription("txtProductDescription" & index)
End Sub
Private Sub CreatetxtProductDescription(id As String)
Dim txt As New TextBox
txt.ID = id
pnltxtProductDescription.Controls.Add(txt) ' THIS IS WHERE I AM GETTING THE ERROR
Dim lt As New Literal With {
.Text = "<br />"
}
pnltxtProductDescription.Controls.Add(lt)
End Sub
Protected Sub Page_PreInit(sender As Object, e As EventArgs) Handles Me.PreInit
Dim keys As List(Of String) = Request.Form.AllKeys.Where(Function(key) key.Contains("txtProductDescription")).ToList()
Dim i As Integer = 1
For Each key As String In keys
CreatetxtProductDescription("txtProductDescription" & i)
i += 1
Next
End Sub
结束班
答案 0 :(得分:2)
它失败的原因是您从CreatetxtProductDescription()
事件中呼叫PreInit
。在初始化控件之前会触发PreInit
,包括您的Panel
控件(请参阅ASP.Net Page Life Cycle)。由于尚未创建Panel
控件,因此当您尝试访问NullException
属性时,它会抛出.Controls
错误。
要解决您的问题,请将PreInit
事件中的代码移至Load
事件。