0
page = (Page)HttpContext.Current.CurrentHandler;
TextBox txtEndUser = ((TextBox)page.FindControl("txtEndUser"));

Here txtEndUser always comes as null.

How can we fix this ?

teenup
  • 7,459
  • 13
  • 63
  • 122

3 Answers3

0

If the page does not directly contains the TextBox control, then you wont be able to retrieve it with the FindControl function. You need to create a function that search contained containers for the target control ..

Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
0

It appears to me that this code snippet is in HttpModule so probably, the request has not been handed out to a handler yet (for example, you're in BeginRequest).

Reference: Why HttpContext.Current.Handler is null?

Community
  • 1
  • 1
Ahmed Magdy
  • 5,956
  • 8
  • 43
  • 75
  • Here Handler is not coming as null, Handler is perfectly set to the Page object and I am using other members of Page object. Rather, the txtEndUser is coming out as null, I am using this code in a Class method that is being called from a UserControl loaded in a Sharepoint Webpart which itself is in asp.net Page. – teenup Jun 15 '11 at 12:49
0

As a workaround if you don't find the way using FindControl you can add public getter to your custom page class the have something like this:

WebForm1 myForm = (WebForm1)HttpContext.Current.CurrentHandler;
TextBox txtEndUser = myForm.GetEndUserTextbox();
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
  • Thanks, but I knew this method, I wanted to know the reason why the above code is not working. – teenup Jun 15 '11 at 12:50
  • @Puneet dunno, quick test with one Page and static class did work, so you probably have something "fancy" like Module? Or maybe you run the code before the `Page_Load` event? – Shadow The GPT Wizard Jun 15 '11 at 12:53
  • I am running the code on a Button's OnClick event which is probably after Page_Load, but don't know why its not working. – teenup Jun 15 '11 at 12:57
  • @Puneet so please add this information to your question by editing it, plus give more code - give the code in that "arbitrary class" you have. – Shadow The GPT Wizard Jun 15 '11 at 13:05