用户控制错误对象引用不设置到对象的实例? [英] User Control error Object reference not set to an instance of an object?

查看:181
本文介绍了用户控制错误对象引用不设置到对象的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 WebUserControl

1. UC_1.axcx
2. UC_2.ascx

我试图访​​问 UC_2.ascx.cs 办法从我的 UC_1.axcx.cs 。以下是
UC_1.ascx.cs 方法。

I tried to access UC_2.ascx.cs method from my UC_1.axcx.cs. Below is UC_1.ascx.cs method.

protected void Page_Load(object sender, EventArgs e)
{
    UC_2 objUC = new UC_2();
    objUC.assignName("123');
}

UC_2.ascx.cs

public string assignName(string nameParam)
{
  TextBox1.Text = nameParam;   //Here i am getting object null error.
  retrun "access UC_2 successfully.";
}

虽然从 UC_1 访问 UC_2 方法,我得到:

对象引用未设置到对象的实例。

Object reference not set to an instance of an object.

如何解决这个问题?

推荐答案

您需要注册 UC_2.ascx UC_1.ascx ,而不是实例化。在 UC_1.ascx

You need to register UC_2.ascx in UC_1.ascx instead of instantiate it. in UC_1.ascx :

<%@ Register Src="~/UC_2.ascx" TagPrefix="uc1" TagName="UC_2" %>

<uc1:UC_2 runat="server" ID="UC_2" />

而在 UC_1 code后面的变化的Page_Load 是这样的:

And in the UC_1 code behind change Page_Load like this:

protected void Page_Load(object sender, EventArgs e)
{
    UC_2.assignName("123");
}

修改:要调用动态 UC2 方法,无需注册在 ASCX ,试试这个

Edit: To call UC2 method dynamically without register in ascx, Try this:

var Uctrl = (UC_2)LoadControl("~/UC_2.ascx"); 
Controls.Add(Uctrl);
Uctrl.assignName("123");

这篇关于用户控制错误对象引用不设置到对象的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆