user2293746
user2293746

Reputation: 11

String To TextBox id

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..

Upvotes: 0

Views: 627

Answers (2)

Sandip
Sandip

Reputation: 481

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

Upvotes: 0

Matthew Haugen
Matthew Haugen

Reputation: 13286

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.

Upvotes: 1

Related Questions