Click here to Skip to main content
15,911,785 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
this.GetType().GetField("TextBoxName").GetValue(this).ToString();

Using this code i try to Retrieve TextBoxName.Text when user supplies the string "TextBoxName" but i get a nullreferencexception.
Posted
Updated 14-Feb-15 5:09am
v5
Comments
OriginalGriff 14-Feb-15 11:01am    
"Didnt Work!" is not a good error report - we have no idea what problem you are having, or what kind of help you are seeking.

Please, try to think about how you present the problem from the POV of the reader: Remember that we can't see your screen, access your HDD, or read your mind.

So try explaining this as if to someone on the other end of a phone, and perhaps that would help...

Use the "Improve question" widget to edit your question and provide better information.
BillWoodruff 14-Feb-15 18:32pm    
Without knowing the context of this cryptic line of code, and what the two uses of 'this refer to ... there's no point in making a guess.
Sinisa Hajnal 16-Feb-15 2:35am    
Why not use TextBoxName.Text? Try to improve question so that we know what you're trying to do, is this winforms, web, wcf...what is "this" in your code (you gave us no context).
gggustafson 16-Feb-15 10:57am    
I believe that the Null Reference Exception is caused when this.GetType().GetField("TextBoxName").GetValue(this).ToString(); returns null. Are you testing for null? If not do so. Remember that anything that a user supplies should be considered as suspect. So if the user enters "foofoo" as the text box name, you will probably fail at GetField("foofoo").

Your issue is that most likely the control being searched for is private or simply non-public. In the GetField call you should add Binding Flags to allow searching for the private / protected fields, if that's what you really want to do.

C#
// replace "txtBoxName" with the actual text form the text box.
FieldInfo info = this.GetType().GetField("txtBoxName", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

if (null != info) {
    // Here get the value as an object or string if you 'know' it will always be a string
    object val = info.GetValue(this);
}
 
Share this answer
 
Try it...
C#
<pre lang="c#">
(this.FindControl("textboxname") as TextBox ).Text
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900