How to convert maskedtextbox value to int if it's empty? - c#

I am building this C# windows application. On a certain Form, I am using maskedtextbox to enter upto 3 numerical digits, then I convert it into int as I have to send all these data to database with an insert query, but the problem is that these maskedtextboxes give error when left empty:
int scd_user_comm = Convert.ToInt32(maskedTextBox1.Text);
and the error is :
Input string was not in a correct format.
The corresponding field in database allows null, so if left empty, it must not give an error. Can anyone help please?
One side question:: Can I use a textbox or maskedtextbox to ensure that user only enters numeric value b/w 0 to 100? Thanks in advance.

You could try the Int32.TryParse() method
int scd_user_comm;
if(Int32.TryParse(maskedTextBox1.Text, out scd_user_comm) == false)
scd_user_comm = 0;
this will give you all the flexiblity required to work with your integer var and your maschedTextBox-
To force your maskTextBox to accept only numeric values set
maskTextBox1.Mask = "999";
maskTextBox1.TextMaskFormat = MaskFormat.ExludePromptAndLiterals;
However this is not enough to ensure the enterd number is between 0 and 100.
To get this result you need to use the Validating event and reject the input if is outside your limits
private void maskedTextBox1_Validating(object sender, CancelEventArgs e)
{
int num;
if (Int32.TryParse(maskedTextBox1.Text, out num) == true)
{
if (num < 0 || num > 100)
{
MessageBox.Show("Insert number between 0 and 100");
e.Cancel = true;
}
}
}

You could use the TryParse instead:
int scd_user_comm;
if(!Int32.TryParse(maskedTextBox1.Text, out scd_user_comm))
{
// Do something to notify the user that the text isn't a number.
}

Related

How do I make a richtextbox limited to only digits with a max number? (Cap)

Hey guys I wanted to make a richtextbox that only supports numbers and cant go above, 500 for example.
how would I go by doing that? thanks
I would use the keydown event to check if the pressed key is one of the keys you allow. With numbers it is pretty simple, maybe add ',' and '.' or other characters of your choice.
I'm not sure about the specifics but you can add something like
myRichTextBox.OnTextChanged() {
int number = 0;
bool checkInt = Int32.TryParse(myRichTextBox.Text, out number); //this checks if the value is int and stores as true or false, it stores the integer value in variable "number"
if ( checkInt = true && number > 500 ) //check if value in textbox is integer
{
myRichTextBox.Text = number.ToString();
}
else
{
DialogBox.Show("Please Enter Numbers Only");
myRichTextBox.Text = "";
}
}
You probably have to read the Int32.TryParse usage but brushing up this code should do what you want.
You can also put this code in a button onclick method to check that the value in textbox is integer before using the text.

How to check if textbox contains only zero and display an alert message?

I use windows forms with C# . I have a form with button1 and textbox1.
What I want is: When I click button1, display alert message if the textbox1 contains any zero or zeros (any combination of zeros only) something like:
0
00
0000
000
000000000
I tried the following code but it will not work if textbox1 has more than one zero (like 000)
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
MessageBox.Show("Enter Value larger than zero);
}
How can I get alert message if textbox1 has any combination of zeros when button1 is clicked?
You can just trim the 0 char by doing something like this:
var text1 = "00000000";
var text2 = "00009000";
Console.WriteLine("Text1: {0}", string.IsNullOrWhiteSpace(text1.Trim('0')));
Console.WriteLine("Text2: {0}", string.IsNullOrWhiteSpace(text2.Trim('0')));
Which returns:
Text1: true
Text2: false //Because we have 9 in the middle of the text.
In your code you will have something like this:
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text.Trim('0'))
MessageBox.Show("Enter Value larger than zero");
}
You can check if the string contains only zeros (0) like this
var str = "000000000";
var isZero = str.All(c => c == '0');
Or with Regex
var isZeroWithRegex = Regex.IsMatch(str, "^0+$");
int value = Convert.ToInt32(textBox1.Text);
if(value ==0)
{
//show
}
else
{
//do something else
}
You can convert the value to integer to do so. You may need to add some validations for string checking etc though.
From what the question states you want to know if there is any zero in the textbox. the easiest way to do that would be
if (textBox1.Text.Contains("0"))
MessageBox.Show("Enter Value larger than zero);
However if you want to ensure that the value is greater that zero convert it to an int and check.
int numberEntered;
if (!int.TryParse(textBox1.Text,out numberEntered)){
//handle conversion error
}
if (numberEntered == 0)
MessageBox.Show("Enter Value larger than zero);`
You can just use:
int convertedText=Convert.ToInt32(textBox1.Text);
if(convertedText==0)
{
...
}
I'll explain to my way . First i am replacing all "0" an than check length because if this text has "0" more than one length not equals 0 otherwise length must be 0
if(textBox1.Text.Replace("0","").Length==0)
To do this do:
private void button1_Click(object sender, EventArgs e)
{
if ( int.Parse(textBox1.Text) == 0)
MessageBox.Show("Enter Value larger than zero");
}
That will turn the string in to an int, and 00, 000, 0000, etc, is equal to 0.

Checking a TextBox for an empty string, an integer or a string

I am checking a text box for the following
If there is no input
If the input is between 0 and 100
If the input is a string other than a number
The code -
if (this.BugCompPct.Text == String.Empty)
else if (Convert.ToInt32(this.BugCompPct.Text) > 100 | Convert.ToInt32(this.BugCompPct.Text) < 0)
//Not sure about checking the last if
What could I put as the if conditional to check for a string other than an integer?
I want only the input to be an integer and nothing else
Thanks
What could I put as the if conditional to check for a string other
than an integer?
Use int.TryParse method to see if the parsing is succesfull.
For empty string use string.IsNullOrWhiteSpace (supported on .Net framework 4.0 and later), For .Net framework 3.5 or lower you can use string.IsNullOrEmpty with string.Trim
Your check will all the conditions could be like:
if (!string.IsNullOrWhiteSpace(BugCompPct.Text))
{
int temp;
if(int.TryParse(BugCompPct.Text,out temp)
{
if(temp >= 0 && temp <= 100)
{
//valid number (int)
}
else
{
//invalid number (int)
}
}
else
{
//Entered text is not a number (int)
}
}
else
{
//string is empty
}
First check if TextBox is empty, then if string is valid number and last check boundaries.
int number = 0;
if (string.IsNullOrEmpty(this.BugCompPct.Text)
{
//not valid
}
else if (Int32.TryParse(this.BugCompPct.Text, out number))
{
if (number > 0 && number < 100)
{
//valid
}
}
every value put into a textbox is as string. I would then advise you to tryparse rather than convert.to.
(Why? tryparse can be handled much easier and won't crash and burn if there are bad values put into it)
just use int.TryParse(txtbox1.text, out i)
You must define integer i above this
then you can use if statements using i (the integer version) to validate it.
To check if its an integer only just use:
if(!int.TryParse(txtbox1.text, out i))
{
// do work
}
then you can use > < in if statements to check how big the number is.
If you are on windows form you should use masked textbox.

How can I determine if a number entered by a user will be misrepresented when stored as a Single in C#?

I have a datagrid that a user will modify. One column stores a Single preciion float. When a user enters a number longer than 7 digits, the number is displayed in scientific notation, and comparisions to the number become very inaccurate. I would like to warn the user that the number is only being stored approximatley when this happens. Is there any way to determine when a number will be stored properly in a single? The cutoff seems to be about 7 digits. Anything more than that and it is way off.
I think you need a validate on each cell.
Explain step by step:
Add CellValidating Event To DataGridView by designer or code:
dataGridView1.CellValidating+=dataGridView1_CellValidating;
Check that you want in it like this:
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
double value = 0;
if (double.TryParse(e.FormattedValue.ToString(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out value))
{
dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = "";
// e.Cancel = false;
}
else
{
dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = "Bad Input Please Correct It !";
// e.Cancel = true; if you do this the datagrid dont let user go next row
}
}
If you want correct the value your self do these step too:
Add CellValidated event too:
dataGridView1.CellValidated+=dataGridView1_CellValidated;
And do this check in that:
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1[e.ColumnIndex, e.RowIndex].Value == null)
return;
double value = 0;
if (double.TryParse(dataGridView1[e.ColumnIndex,e.RowIndex].Value.ToString(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out value))
{
dataGridView1[e.ColumnIndex, e.RowIndex].Value = Math.Round(value, 2).ToString().Replace("/",".");
}
}
Note : This event occurs each time a cell edit if you want do these on special cell check it before event raise. You can set max Input length for each column to avoid bad input.
You could always just check for yourself by parsing the input and turning it back into a string:
string s = "0.12345678";
return Single.Parse(s).ToString() == s;
the second you store any number in a float or double assume it's no longer 100% accurate, because odds are it's not. The second you perform any operations on the number, particularly if it's anything other than addition/subtraction, you can be fairly sure there is some error. If you want to know exactly how much error their is, then you start to get into some pretty complex mathematics.

How do I put a textbox entry into while loop? C#

This is essentially what I am trying to do. I want to allow someone to enter a number on how many times they want to run a specific program. What I can't figure out is how to change the number 10 into (textBox1.Text). If you have a better way please let me know. I am very new to programming.
int counter = 1;
while ( counter <= 10 )
{
Process.Start("notepad.exe");
counter = counter + 1;
}
This shows how to take the user-supplied input and safely convert it to an integer (System.Int32) and use it in your counter.
int counter = 1;
int UserSuppliedNumber = 0;
// use Int32.TryParse, assuming the user may enter a non-integer value in the textbox.
// Never trust user input.
if(System.Int32.TryParse(TextBox1.Text, out UserSuppliedNumber)
{
while ( counter <= UserSuppliedNumber)
{
Process.Start("notepad.exe");
counter = counter + 1; // Could also be written as counter++ or counter += 1 to shorten the code
}
}
else
{
MessageBox.Show("Invalid number entered. Please enter a valid integer (whole number).");
}
textBox1.Text will return a string. You need to convert it into an int and since it's taking user input, you'll want to do so safely:
int max;
Int32.TryParse(value, out max);
if (max)
{
while ( counter <= max ) {}
}
else
{
//Error
}
Try System.Int32.TryParse(textBox1.Text, out counterMax) (Docs on MSDN) to convert a string to a number.
This will return a true if the conversion succeeded or a false if it failed (i.e., the user entered something that isn't an integer)
I would suggest to use MaskedTextBox control to take input from user, which will help us to ensure that only numbers will supplied. It will not bound us for TryParse functionality.
Set mask like this: (can use "Property Window")
MaskedTextBox1.Mask = "00000"; // will support upto 5 digit numbers
then use like this:
int finalRange = int.Parse(MaskedTextBox1.Text);
int counter = 1;
while ( counter <= finalRange )
{
Process.Start("notepad.exe");
counter = counter + 1;
}
use Try Catch body ,like this function
bool ErrorTextBox(Control C)
{
try
{
Convert.ToInt32(C.Text);
return true;
}
catch { return false; }
}
and use

Categories