0

i am using asp.net 2.0 i need help for string Value to Textbox id..I am already declare textbox in source that id in string value..i have more than ten textbox.but textbox id serial number i set value all text box same time same value i use below code

for (int i = 1; i <= 12; i++)
{
    String _control = "txt_capex_" + i.ToString().Trim();
    TextBox txt = FindControl(_control) as TextBox;
    txt.Text = _splitamount.ToString().Trim();
}

i get Error in

System.NullReferenceException was unhandled by user code Message="Object reference not set to an instance of an object.

what solution for this..

Sayse
  • 42,633
  • 14
  • 77
  • 146

2 Answers2

1

Is it fair to assume all of your textboxes aren't lying on the page itself? That is, you probably have some nested in Panels, GridViews, or other similar controls. Particularly if you're adding them dynamically, which I assume you are. Make sure you're calling the parent's FindControl method, not just the page's.

Page.FindControl:

This method searches only the page's immediate, or top-level, container; it does not recursively search for controls in naming containers contained on the page. To access controls in a subordinate naming container, call the FindControl method of that container.

The other possibility is that you're casting to the wrong type. Because you're using the as keyword as compared to conventional (Type)value casting, that expression will resolve to null if the FindControl method returns anything that can't be assigned to a TextBox value, as compared to the traditional throwing of an exception.

Matthew Haugen
  • 12,916
  • 5
  • 38
  • 54
  • TextBox txt = FindControl(_control) as TextBox (or)TextBox txt = (TextBox)FindControl(_control); both Object reference not set to an instance of an object – user2293746 Jul 16 '14 at 07:16
  • Yes, I figured. I very much expect that it's a matter of mistaking the `TextBox`'s parent. – Matthew Haugen Jul 16 '14 at 07:21
0

either FindControl or _splitamount return NullReferenceException.Please debug your code.also if possible can you please put StackTrace of your error here ?

Sandip
  • 481
  • 1
  • 9
  • 26
  • at System.Web.UI.WebControls.TextBox.OnTextChanged(EventArgs e) at System.Web.UI.WebControls.TextBox.RaisePostDataChangedEvent() at System.Web.UI.WebControls.TextBox.System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() at System.Web.UI.Page.RaiseChangedEvents() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) – user2293746 Jul 16 '14 at 08:24
  • Message="Object reference not set to an instance of an object." Source="App_Web_-di-a3lt" – user2293746 Jul 16 '14 at 08:26
  • it clears that your FindControl() could not find proper control. – Sandip Jul 17 '14 at 12:28
  • can you please tell me do you want dynamic generation of Textbox or finding Textbox from Gridview ? – Sandip Jul 18 '14 at 06:54