0

I am trying to convert a textBox entry into an integer value so it can be used in an equation. When I try create the int value using

 int number1 = int.Parse(num1.Text);

I get an error:

A field initializer cannot reference the non-static field, method, or property 'Tutorial_Form.Form1.num1'

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Reuben Ward
  • 101
  • 1
  • 9
  • where do you have this statement of code? – Adil Sep 26 '14 at 05:35
  • You can use int number1=convert.Toint(num1.text); – MMM Sep 26 '14 at 05:35
  • Are you putting this inside a method or a class declaration(it wont work here) ? Also you can try Convert.ToInt32() – Abdul Rehman Sayed Sep 26 '14 at 05:35
  • 1
    You'd need to move this to the constructor body in order to do it as part of initialization. It's hard to tell what you're trying to do from just a single line of code though. More context would really help. – Jon Skeet Sep 26 '14 at 05:36
  • @JonSkeet I suspect he actually meant to put this in a `Click` event (or something like that), putting it in the constructor would accomplish the same thing as this field initializer would, but that would be pretty useless, since the textbox would just have been created. Just for the record. – Matthew Haugen Sep 26 '14 at 05:38
  • Side note: instead of "searched alot"/"tried alot" text in your question please show links to questions/articles you've found and code you've tried. It will make helping you much easier. – Alexei Levenkov Sep 26 '14 at 05:52
  • @MatthewHaugen: Possibly. It's hard to tell. But the textbox could have been created with some existing text... – Jon Skeet Sep 26 '14 at 05:52
  • @JonSkeet Oh, yeah, no, I'm definitely not disagreeing with what you said. There's not enough information to know what's truly going on. I was just adding on to that, saying that what it looks like is happening is probably not what he *meant* to do. But certainly, we need to see more code to draw any conclusions. – Matthew Haugen Sep 26 '14 at 06:16

1 Answers1

1

You would have to put the code to set that field in a method.

Does it really make sense to initialise a field using the contents of a TextBox though? The user can't possibly have entered anything into the control, so there's no integer to parse. You need to consider when it is that you want to get the number from the input and put your code there, e.g. the Click event handler of a Button.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46