-5
converted.Year = textBox2.Text;
textBox17.Text = converted.Year;

int year2 = int.Parse(converted.Year);
converted.Year = year2.ToString();

Hi! I would like the final assigned value of textBox17 to be of an int type.

Initially, I tried: textBox17.Text = int.Parse(converted.Year);

But it only returns an error message that it can't do the conversion.

So I came up with the 2 last lines, but I'm not really sure if it really outputs an int? I think I probably have walked in circles around the problem? Hmm...

Brian
  • 5,069
  • 7
  • 37
  • 47
  • 1
    Int.Parse is going to take a string that already has an int-compatible value (such as "32") and convert it into an Int object (32). That doesn't seem to be what you're trying to do. Can you give more details? – McAden Jan 23 '13 at 23:00
  • The type of `textBox17.Text` is not `int`. It's `string`, that's why you cannot assign an `int` to it. – Brian Rasmussen Jan 23 '13 at 23:01
  • Possible duplicate: http://stackoverflow.com/questions/405619/convert-string-to-int-and-test-success-in-c-sharp – Tim Lehner Jan 23 '13 at 23:01
  • 5
    You could have at least tried to use variables that are more meaningful than `converted` or `textbox17`. – Tim Schmelter Jan 23 '13 at 23:02
  • If you're just trying to validate that converted.Year can be parsed as an integer, look into int.TryParse(converted.Year). – MadHenchbot Jan 23 '13 at 23:06
  • What type does `converted.Year` have? – Mr Lister Jan 23 '13 at 23:10

3 Answers3

3

The type of textbox17.Text is string and will always be string. You can certainly use it to display integers though.

There is a NumericUpDown control you can use to display numbers that accepts only numbers. To force integer display just set its DecimalPlaces property to 0.

Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
  • I want the numerical string value entered in textBox2, show up in textBox17 as an int value. is it possible ? – Crystalise Moriwaki Jan 23 '13 at 23:10
  • @CrystaliseMoriwaki: Yes it is. You need to add a TextChanged event handler to textBox2. In the handler read the string value in textBox2 and do an int.TryCast() on it. If the cast works, assign it to textBox17. If not, set it to "error" or some message of your choice. – Paul Sasik Jan 23 '13 at 23:13
2

You've got:

converted.Year = textBox2.Text;
textBox17.Text = converted.Year;

This is valid although all you're doing is copying a string around.

Then you've got:

int year2 = int.Parse(converted.Year);

Which is also fine - but will crash if the string isn't representative of an int ("32" is fine, "bob" will crash as will "32bob")

Then you've got:

converted.Year = year2.ToString();

Which, if it hasn't crashed - shouldn't give any value different from your first line above.

McAden
  • 13,714
  • 5
  • 37
  • 63
1

The textBox.Text can only accept a string. So you will have to use int.Parse and ToString when getting/setting the text.

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73