To Disable Negative Values Inside a TextBox - c#

I m Working On A windows Form.. I Need my TextBox Not To Accept negative Values ..How Can I Do this..
IS There Any Property Availiable For Doing The same...

You need to write keypress event of textbox like :
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
You can also user numeric updown control to prevent negetive values.
UPDATE :
Ref: Sai Kalyan Akshinthala
My code will not handle the case of copy/paste. User can enter negative values by copy/paste. So I think Sai Kalyan Akshinthala's answer is correct for that case except one small change of Length >= 2.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(textBox1.Text.Length >= 2)
{
int acceptednumber = Convert.ToInt32(textBox1.Text);
if(acceptednumber < 0)
{
textBox1.Text = "";
MessageBox.Show("-ve values are not allowed");
}
else
{
textBox1.Text = textBox1.Text;
}
}
}

yes you can do write the following code part in textchanged event of textbox
if(textBox1.Text.Length >= 2)
{
int acceptednumber = Convert.ToInt32(textBox1.Text);
if(acceptednumber < 0)
{
textBox1.Text = "";
MessageBox.Show("-ve values are not allowed");
}
else
{
textBox1.Text = textBox1.Text;
}
}

just use min and pattern will not allow to enter a minus value
min="0" pattern="^[0-9]+$" in input type

Related

C# How to disable button when the value is zero

I'm a beginner to C# programming and I really need some help :)
I made 2 buttons that will increment or decrement the value in the text box which is initially zero.
private void bminus_Click(object sender, EventArgs e)
{
NUMBER--;
textBox2.Text = NUMBER.ToString();
}
private void bplus_Click(object sender, EventArgs e)
{
NUMBER++;
textBox2.Text = NUMBER.ToString();
}
Will there be a way that the decrement button will be disabled if the value is 0 so that there won't be negative numbers? Thank you, I'd really appreciate anyone's help! :)
private void bminus_Click(object sender, EventArgs e)
{
NUMBER--;
textBox2.Text = NUMBER.ToString();
if(NUMBER == 0){
bminus.Enabled = false;
}
}
private void bplus_Click(object sender, EventArgs e)
{
NUMBER++;
textBox2.Text = NUMBER.ToString();
bminus.Enabled = true;
}
That should do.
You can just directly insert logical state NUMBER not being 0 to your textBox2 Enabled property:
textBox2.Enabled = NUMBER != 0;
Or make a separate function from this:
private bool IsNotZero(double n)
{
return n != 0;
}
then:
textBox2.Enabled = IsNotZero(NUMBER);
All you need to do is add the following to the textBox2.TextChanged event handler and it should work with your current code.
private void textBox2_TextChanged(object sender, EventArgs e)
{
int output;
if (int.TryParse(textBox2.Text, out output))
{
bminus.Enabled = int.Parse(textBox2.Text) > 0;
}
}
NOTE: No one here has specified checking for an integer so I added int.TryParse and int.Parse for this purpose.
Button have a property named Enabled which you can set to true or false based on your logic.
Check the value using if condition. If the value is null or zero you can use button.enabled = false; code.if(value == zero || value == null) { button.enabled=false;} else {button.enabled = true;}

Ban enter letters textBox

How to prohibit the introduction of letters in textBox? That is, this construction works incorrectly
public void textBox1_KeyDown(object sender, KeyEventArgs e)
{
try
{
char s = Convert.ToChar(textBox1.Text);
if ((s <= '0') || (s >= '9'))
MessageBox.Show("You have entered a symbol! Please enter a number");
}
catch (System.FormatException)
{
MessageBox.Show("You have entered a symbol! Please enter a number");
}
}
You need to either check the key being entered in the KeyDown event (e.Key property) as the key value is added to the Text field after the event or use the TextChanged event - this would catch cut & paste operations as well.
public void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (!ValidNumericString(textBox1.Text))
{
MessageBox.Show("You have entered invalid characters! Please enter a number");
Dispatcher.BeginInvoke(new Action(() => textBox1.Undo()));
e.Handled = true;
}
}
public bool ValidNumericString(string IPString)
{
return IPString.All(char.IsDigit);
// OR make this check for thousands & decimals if required
}
You can use the OnKeyPress event which allows you to cancel the key event manually if you want to.
void textBox1_OnKeyPress(KeyPressEventArgs e)
{
e.Handled = true; // this won't send the key event to the textbox
}
If you want to accept only numbers and related chars (negative sign, decimal separators, ...), you can test the entered char :
void textBox1_OnKeyPress(KeyPressEventArgs e)
{
NumberFormatInfo numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat;
string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
string groupSeparator = numberFormatInfo.NumberGroupSeparator;
string negativeSign = numberFormatInfo.NegativeSign;
string keyInput = e.KeyChar.ToString();
e.Handled = !(Char.IsDigit(e.KeyChar) || keyInput.Equals(negativeSign) || keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator));
}
This is untested code because I'm at work, but you get the idea.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (Control.ModifierKeys == Keys.Control) return; // Check if ctrl is pressed
var key = (char) e.KeyValue; // ASCII to char
if (char.IsDigit(key) || char.IsControl(key) || char.IsWhiteSpace(key)) return; // Check if "key" is a number
MessageBox.Show("You have entered a symbol! Please enter a number");
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1); // Remove last element
textBox1.SelectionStart = textBox1.Text.Length; // Return to initial position
}

TextBox with maxvalue

I want to make a TextBox which does not allow to enter a value above 100. Only numbers allowed, And a Numeric TextBox is not an option. This is my code for now:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; } // only numbers
}
Any ideas?
You should use int.TryParse to see if the parsing is successful and then compare the value to see if it is below 100.
int number;
if(int.TryParse(textBox1.Text, out number))
{
if(number <= 100)
{
//in range
}
else
{
// not in range
}
}
else
{
//invalid number
}
You can also use double.TryParse or other TryParse method depending on the type, they are safe to use, since they will return a false if the parsing fails, instead of raising an exception.
Hello, here is my solution.
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
if ((!char.IsDigit(c) ||
Convert.ToInt32(textBox.Text + e.KeyChar) >= 101 ||
textBox.Text == "0") && c != '\b')
e.Handled = true;
}
Finally. I found a solution:
int box_int = 0; Int32.TryParse(textBox1.Text, out box_int);
if (box_int > 1050 && textBox1.Text != "") { textBox1.Text = "1050"; }
You can enter only numbers and use arrows keys and backspace. If you enter a number > than 100 or less than 1, when you press enter it will be cancelled. Copy and Past with button key down is disabled and also mouse right click to prevent the user to paste in the text box is disabled/handled. This should solve your problem in full.
First of all set:
ShortcutsEnabled property of your text box to False
this will not allow mouse right click and ctrl+V for paste in your text box.
Then add the following code:
//prevent letters, special chars, punctuation, symbols, white spaces
private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
{
if (char.IsLetter(e.KeyChar) ||
char.IsSymbol(e.KeyChar) ||
char.IsWhiteSpace(e.KeyChar) ||
char.IsPunctuation(e.KeyChar))
e.Handled = true;
}
{
//allows only numbers between 1 and 100
string value = txtType1.Text;
if (txtType1.Text !="")
{
if (Int16.Parse(value) < 1 )
{
txtType1.Text = "";
}
else if (Int16.Parse(value) > 100)
{
txtType1.Text = "";
}
}
}
}

After "." the value entered must replace "00" with two digits only in the textbox

May be My Question is not seems like a good one but here is the Description:
I am creating an application in this in a form i have a textbox which is taking input from user here is my Code
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = string.Format("{0:0.##}", "0.00");
}
this will show value in textbox at pageload:0.00
Now after this if i click on backspace button of keyboard then
if (e.KeyChar.ToString() == ".")
{
e.Handled = true;
int b = textBox1.Text.LastIndexOf("00");
textBox1.SelectionStart = b;
}
else
{
string abc = "0";
string a = textBox1.Text.TrimStart(abc.ToCharArray());
textBox1.Text = a;
}
this code will lead me to here the textbox has now: .00 only
but after this when i enter some value then it will take values as;
2334.3423424
but i want to do like
2334.34
it means value should replace .00 only and user cant enter value after that.
This piece of code will restrict your user in entering only 2 digits after the decimal in your textbox.
//In key press event:
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar))
{
TextBox tt = (TextBox)sender;
if (tt.Text.IndexOf('.') > -1 && tt.Text.Substring(tt.Text.IndexOf('.')).Length >= 3)
{
e.Handled = true;
}
}
If you mean to say you want to round up a number up to two decimal places use Math.Round(Double, Int32) function.
In your case you could call
double value = Convert.ToDouble(textBox1.Text);
double finalValue = Math.Round(value, 2);
textBox1.Text = finalValue.ToString();
Also make sure you validate the user input and make sure the user only enters numeric values.

Textbox display formatting

I want to add "," to after every group of 3 digits. Eg : when I type 3000000 the textbox will display 3,000,000 but the value still is 3000000.
I tried to use maskedtexbox, there is a drawback that the maskedtexbox displayed a number like _,__,__ .
Try adding this code to KeyUp event handler of your TextBox
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
int valueBefore = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);
textBox1.Text = String.Format(culture, "{0:N0}", valueBefore);
textBox1.Select(textBox1.Text.Length, 0);
}
}
Yes, it will change the value stored in a texbox, but whenever you need the actual number you can use the following line to get it from the text:
int integerValue = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);
Of course do not forget to check that what the user inputs into the textbox is actually a valid integer number.
Use String.Format
int value = 300000
String.Format("{0:#,###0}", value);
// will return 300,000
http://msdn.microsoft.com/en-us/library/system.string.format.aspx
This may work fine for your scenario I hope.
private string text
{
get
{
return text;
}
set
{
try
{
string temp = string.Empty;
for (int i = 0; i < value.Length; i++)
{
int p = (int)value[i];
if (p >= 48 && p <= 57)
{
temp += value[i];
}
}
value = temp;
myTxt.Text = value;
}
catch
{
}
}
}
private void digitTextBox1_TextChanged(object sender, EventArgs e)
{
if (myTxt.Text == "")
return;
int n = myTxt.SelectionStart;
decimal text = Convert.ToDecimal(myTxt.Text);
myTxt.Text = String.Format("{0:#,###0}", text);
myTxt.SelectionStart = n + 1;
}
Here, myTxt = your Textbox. Set Textchanged event as given below and create a property text as in the post.
Hope it helps.
You could hook up to OnKeyUp event like this:
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (!(e.KeyCode == Keys.Back))
{
string text = textBox1.Text.Replace(",", "");
if (text.Length % 3 == 0)
{
textBox1.Text += ",";
textBox1.SelectionStart = textBox1.Text.Length;
}
}
}
Get Decimal Value Then set
DecimalValue.ToString("#,#");

Categories

Resources