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 ?

3
  • Who creates the TextBox1? In any case, recommended reading What is a NullReferenceException and how do I fix it? Commented Jul 11, 2015 at 10:53
  • In My UC_2.ascx I have <asp:TextBox id="TexBox1" Text="test" runat="server"/>. So i would like replace value "test" tp "123" whhile assign the value via UC_1. That time i am getting null reference issue. Commented Jul 11, 2015 at 10:59
  • I can't understand your recommended link. Can you please help me to solve Commented Jul 11, 2015 at 11:00

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

1 Comment

If it's possbile to call UC2 method dynamically without register in ascx.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.