❔ I need help to convert a string type of textbox text to int
I have a textbox to enter a number
then I wanna get number in a int variable
20 Replies
What have you tried so far?
System.Convert.ToInt32(Txt.Text)
int x = int.Parse(Txt.Text)
it gives me errors
System.FormatException: 'Input string was not in a correct format.'
how can i fix it?
can you help me?
@Haze.
@ǃ THE REAL DRAGON AKUMA when you get value from textbox, is this in decimal format?
Like 1.00
no
it's int like 32
int x = Convert.ToInt32(Txt.Text);
I tried it
but it didn't work
This statement should be work.
also you can remove extra spaces if any come
with using Trim() Method
like Txt.Text.Trim()
generally speaking, u shouldnt use
Convert
for this, but instead int.TryParse(string, out int)
:
but besides that i guess its what sumit is thinking: random whitespaces, so sanitizing the input before passing it would be the correct way
TryParse(...)
(and usually all these TrySomething(...)
methods) return a bool value if it succeeded or not.
the out
is a bit complexer:
imagine i would have instead written:
the out
basically means, that the method TryParse
will assign a value to the given variable (number
), which u can then use to further process ur stuff.
having it out int number
instead just means that its declaring the variable there, instead of before the if
(its mainly syntactical sugar ;p)don't use convert, use tryparse instead
you can do it like this for example
SlimStv#2835
REPL Result: Success
Console Output
Compile: 578.933ms | Execution: 35.671ms | React with ❌ to remove this embed.
depends on your setup, you may not need the regex there
thanks u
i mentioned it already
this as is, i wouldnt recommend tho. its valid to complain to the user that their input is garbage ;p
(especially since that example is a valid integer in hex format ;p)
if it answers your question @ǃ THE REAL DRAGON AKUMA you can close this
ok wait i'm copying codes
yeah based on your posted code, you'd need to make sure that they're all numbers
my code would bypass that but in production, you don't want that
you can check if your string contains numbers o via
char.IsDigit
its all a matter of how vague u want to allow the user input.
for explicit stuff, use the
TryParse
method.
after that comes more complecity, sanitizing strings, culture based input formats and so on.
given ur current knowledge i would say trimming whitespaces to sanitize and TryParse
is what u should go for
if u do not have further questions, remember to $close the thread 😉Use the
/close
command to mark a forum thread as answeredofc if u have more question regarding this topic ask ;p
i have explained the
out
part in more detail here if u want a deeper understanding of it: https://discord.com/channels/143867839282020352/1105905561591087144/1106118506803634246Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.