Answered by:
Textbox must accept only numbers and '.'

Question
-
My textbox must accept only numbers and coma.
String in textbox must be a decimal number.. I must prevent user to input for example 12..34 or .2.2.33 ...
I want to create some kind of function to check textbox input:
public bool isStringDouble(TextBox tb) { }
Answers
-
I solve it like this:
private bool isTextboxInputDecimal(TextBox textbox) { try { Convert.ToDouble(textbox.Text); MessageBox.Show("ok"); return true; } catch { MessageBox.Show("error"); return false; } }
- Marked as answer by wartmignef Friday, March 25, 2011 2:43 PM
All replies
-
This is where you would want to use some type of regular expression. See this site for may examples http://www.regexlib.com/. Hope this helps.
-
Hi,
meybe NumericUpDown Control (Windows Forms)?
BR, Karol. mark as answer/vote as helpful if it helped you -
Check out this code:
public partial class Form1 : Form { public Form1() { InitializeComponent(); textBox1.TextChanged += new EventHandler(textBox1_TextChanged); } bool bOneTime; private void textBox1_TextChanged(object sender, EventArgs e) { string value = textBox1.Text; if (!bOneTime) { if (value != String.Empty) { if (!IsStringDouble(value)) { bOneTime = true; textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1, 1); textBox1.SelectionStart = textBox1.Text.Length; } } } else bOneTime = false; } private bool IsStringDouble(string str) { double d = 0; if (double.TryParse(str, out d)) { if (str.Contains("..") || str.Contains(",")) return false; else return true; } else return false; } }
Hope it helps,
Mitja
- Proposed as answer by Levi Domingos Friday, March 25, 2011 5:02 PM
-
I solve it like this:
private bool isTextboxInputDecimal(TextBox textbox) { try { Convert.ToDouble(textbox.Text); MessageBox.Show("ok"); return true; } catch { MessageBox.Show("error"); return false; } }
- Marked as answer by wartmignef Friday, March 25, 2011 2:43 PM
-
And this is all the code which accepts Only decimals into textBox? I think not. Didnt you talking about having all the code for it?
And besised, your code will NOT work. What will happen if you type 2 dots, ot a comma? Check it out by your self.
You better double check my exampe code.
btw, and next time please do not answer on your own created threads, if the solution pasted is not completely going along with the thread`s title (rules).
Mitja