0

I have two WebUserControl.

1. UC_1.axcx
2. UC_2.ascx

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.";
}

While accessing UC_2 method from UC_1, I am getting:

Object reference not set to an instance of an object.

How to solve this issue ?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Dhamo
  • 91
  • 4
  • 14
  • Who creates the TextBox1? In any case, recommended reading [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Steve Jul 11 '15 at 10:53
  • In My UC_2.ascx I have . So i would like replace value "test" tp "123" whhile assign the value via UC_1. That time i am getting null reference issue. – Dhamo Jul 11 '15 at 10:59
  • I can't understand your recommended link. Can you please help me to solve – Dhamo Jul 11 '15 at 11:00

1 Answers1

2

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" />

And in the UC_1 code behind change Page_Load like this:

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

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");
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109