0

I have two usercontrol UC_1.ascx & Uc_2.ascx.

I tried to bind UC_2 textbox values from my UC_1.

Below is my code :

 System.Web.UI.UserControl UserControl1 = (System.Web.UI.UserControl)Page.FindControl("UC_2");
if (UserControl1 != null)
{
    TextBox txt = UserControl1.FindControl("txtTest") as TextBox; //thwon object null reference error.
    txt.Text = "test123123123213";
}

But I am getting error from calling UserControl1 object.

Error like :

Object reference not set to an instance of an object.

Dhamo
  • 91
  • 4
  • 14
  • You cannot find control like that, refer to this answer http://stackoverflow.com/a/4955836/1432033 – yogi Jul 20 '15 at 06:50
  • `NullReferenceException` is a common situation for beginner programmers. The link provided should help you understand the problem. Then use the debugger to find what/where/when you have a variable that is `null`. – Soner Gönül Jul 20 '15 at 06:51

2 Answers2

0

1) You need to check that your UserControl1 is not null.

2) If it isn't, check that UserControl1.FindControl("txtTest") as TextBox doesn't equal to null.

The code is equivalent to the following expression except that the expression variable is evaluated only one time. expression is type ? (type)expression : (type)null the problem is in the type you try to cast.

israel altar
  • 1,768
  • 1
  • 16
  • 24
-1

Replace TextBox txt = UserControl1.FindControl("txtTest") as TextBox;

by

if(UserControl1.FindControl("txtTest") != null)
{
TextBox txt = UserControl1.FindControl("txtTest") as TextBox; 
txt.Text = "test123123123213";
}

FindControl is not able to locate txtText, Keep in mind that it only searches direct children of the container.

Kryptonian
  • 860
  • 3
  • 10
  • 26