If I have:
<asp:TextBox ID="txtField1" runat="server"></asp:TextBox>
Then in my code-behind I can access that web control by its “ClientID”:
txtField1.Text = "value";
That works, but I want an alternate way to access the same web control by reference so I tried doing it this way:
TextBox myTxtField = (TextBox)Page.FindControl("txtField" + 1);
myTxtField.Text = "value";
And I am getting the error: “Object reference not set to an instance of an object.” Any idea if I am doing this right or if there is another way to reference a web control’s ID by passing in a string?
This returns null if the control is sitting on a ContentPage of a
MasterPage. Then you should reference it directly (as shown below).I’ve written something about this issue here: https://stackoverflow.com/a/8781131/284240
Of course it would also return null if the control has another ID or if it’s in another
NamingContainerthan the page(f.e. in a GridView).Side note:
txtField1is theIDnot theClientIDand actually you’re referencing the control directly.