我在用户控件中有一个文本框。我创建了这个用户控件,并在占位符中加载。
但是当我尝试为文本框分配值时,我在下面提出错误:
Object reference not set to an instance of an object
这是用户控件:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="IVT_FormClient.ascx.cs" Inherits="Evi.Sc.Web.Evi.IVT.Sublayouts.IVT_FormClient" %>
<asp:Panel ID="pnlContainer" runat="server">
<asp:TextBox ID="txtClientNumber" runat="server"></asp:TextBox>
</asp:Panel>
访问修饰符是(在用户控件中):
public string TxtFirstName
{
get { return txtFirstName.Text; }
set { txtFirstName.Text = value; }
}
在网络表单中,我有控件参考:
<%@ Reference Control="~/Evi/IVT/Sublayouts/IVT_FormClient.ascx" %>
在用户控件的代码后面是:
public partial class frm_VerifyIdentity : System.Web.UI.Page
{
IVT_FormClient ivtFormClient = new IVT_FormClient();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
IVT_FormClient ivtFormClient = (IVT_FormClient)LoadControl("~/Evi/IVT/Sublayouts/IVT_FormClient.ascx");
Client UserClient = new Client();
UserClient = Load_ClientVerification(Server.HtmlEncode(Request.QueryString["ID"]).Trim());
if (UserClient != null)
{
ivtFormClient.TxtFirstName = UserClient.FirstName;
plhFormClient.Controls.Add(ivtFormClient);
}
}
}
}
发生错误的是这行代码:
ivtFormClient.TxtFirstName = UserClient.FirstName;
答案 0 :(得分:0)
不要像UserControl
那样在LoadControl
通过构造函数创建实例,而是使用Page_Load
创建实例。但是,您只是if(!IsPostBack)
。因此,控件通过构造函数实例化下一个回发。
此外,您必须在每次回发时重新创建动态控件。我建议将UserControl delaratively添加到页面。您可以相应地隐藏/显示它。否则,您需要始终创建/添加它,最好是Page_Init
而不是Page_Load
。
所以这不是最佳实践(只需将其添加到页面中),但应该按照需要运行:
IVT_FormClient ivtFormClient = null;
protected void Page_Init(object sender, EventArgs e)
{
ivtFormClient =(IVT_FormClient)LoadControl("~/Evi/IVT/Sublayouts/IVT_FormClient.ascx");
Client UserClient = new Client();
UserClient = Load_ClientVerification(Server.HtmlEncode(Request.QueryString["ID"]).Trim());
if (UserClient != null)
{
ivtFormClient.TxtFirstName = UserClient.FirstName;
plhFormClient.Controls.Add(ivtFormClient);
}
}