Restricting textbox input to numbers in C# [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to restrict a textbox to accept only numbers in C#. How do I do that?

The most crude down and dirty way of doing it is doing something like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar);
}
}
You're still not safe with this approach, as users can still copy and paste non-numeric characters into the textbox. You still need to validate your data regardless.

From others have said before me, we have to almost know what you will use this in, WinForms, ASP.NET, Silverlight ...
But now I take a chance that it is WinForm:)
private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
e.Handled = true;
}

has some bugs but easy way :D
private void textbox1_TextChanged(object sender, EventArgs e)
{
char[] originalText = textbox1.Text.ToCharArray();
foreach (char c in originalText)
{
if (!(Char.IsNumber(c)))
{
textbox1.Text = textbox1.Text.Remove(textbox1.Text.IndexOf(c));
lblError.Visible = true;
}
else
lblError.Visible = false;
}
textbox1.Select(textbox1.Text.Length, 0);
}

Have you tried the MaskedTextBox control in WinForms?

Have a look at something like this
Masked C# TextBox Control

This may not be the best way, but works ok for WPF TextBox...
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
string originalText = ((TextBox)sender).Text.Trim();
if (originalText.Length>0)
{
int inputOffset = e.Changes.ElementAt(0).Offset;
char inputChar = originalText.ElementAt(inputOffset);
if (!char.IsDigit(inputChar))
{
((TextBox)sender).Text = originalText.Remove(inputOffset, 1);
}
}
}

You can use the FilterTextBox of AJAX Control Toolkit. Using this you can allow/disallow any character type. This is quite flexible.

You can use the Microsoft.VisualBasic.Information.IsNumeric is numeric function. Just add the reference Microsoft.VisualBasic
private void textBox1_Validating(object sender,
System.ComponentModel.CancelEventArgs e) {
if (!Microsoft.VisualBasic.Information.IsNumeric(textBox1.Text)) {
e.Cancel = true;
} else {
// Do something here
}
}
This allows the user to enter scientific notation which is not trivial to filter for.

Not sure if this is the correct way, but it works for me, running it on the TextChanged event TextBox has:
private void CoordinateValidation(object sender, TextChangedEventArgs e) {
TextBox inputBox = e.OriginalSource as TextBox;
inputBox.TextChanged -= CoordinateValidation;
int caretPos = inputBox.CaretIndex;
foreach (TextChange change in e.Changes) {
if (inputBox.Text.Substring(change.Offset, change.AddedLength).Any(c => !ValidChars.Contains(c)) ||
inputBox.Text.Count(c => c == '.') > 1 ||
(inputBox.Text.Length > 0 && inputBox.Text.Substring(1).Contains('-'))) {
inputBox.Text = inputBox.Text.Remove(change.Offset, change.AddedLength);
caretPos -= change.AddedLength;
}
}
inputBox.CaretIndex = caretPos;
inputBox.TextChanged += CoordinateValidation;
}

Have a look at the below code
private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
This will be helpful but users can Copy and Paste characters :-)

Related

How to enable button after all textboxes are not empty in c# winforms?

How can I make button property set to enabled=true after all my textboxes are not empty?
I'm learning programming and my apps are simple.
I know how to enable this property when one of my textboxes have text but this is not the case.
Use case is that user need to put data in both textboxes and after that will be able to click btn.
How in most simple way can I validate all form and then enable button?
There are just 2 tb:
https://i.imgur.com/JUslNWE.png
You need to create a TextBox_TextChanged event and subscribe to all text boxes.
private void TextBox_TextChanged(object sender, EventArgs e)
{
int notEmptyTextBoxCount = 0;
int textBoxCount = 0;
foreach (var item in Controls)
{
if (item is TextBox txtb)
{
textBoxCount++;
if (txtb.Text != String.Empty)
notEmptyTextBoxCount++;
}
}
if (textBoxCount == notEmptyTextBoxCount)
button.Enabled = true;
else
button.Enabled = false;
}
Thanks guys for all feedback.
I have managed to do this this way:
private void ValidateTextBoxes()
{
if (loginTextBox.Text.Length != 0 && passTextBox.Text.Length != 0)
{
generateHashBtn.Enabled = true;
}
else
{
generateHashBtn.Enabled = false;
}
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
ValidateTextBoxes();
}
private void TextBox2_TextChanged(object sender, EventArgs e)
{
ValidateTextBoxes();
}

C# windows forms - How can I only allow integers to be input into textboxes? [duplicate]

This question already has answers here:
numeric-only textbox as a control in Visual Studio toolbox
(4 answers)
How do I make a textbox that only accepts numbers?
(41 answers)
Closed 5 years ago.
I am fairly new to C#, and this is my first attempt at creating a windows form. I created a very simple calculator which has two textboxes for users to enter numbers into. It has a(n) Add, Subtract, Multiply, and Divide button, and when the user enters values into the textboxes and clicks one of the buttons, the result is shown in a label. I would like to only allow integers to be input into the textboxes, but I don't know how I would be able to do this. Any advice or recommendations are appreciated. Thanks.
Here is my code so far:
namespace SimpleCalc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void AddBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
ResultLbl.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
private void SubtractBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
ResultLbl.Text = (Convert.ToInt32(textBox1.Text) - Convert.ToInt32(textBox2.Text)).ToString();
}
private void MultiplyBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
ResultLbl.Text = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text)).ToString();
}
private void DivideBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
ResultLbl.Text = (Convert.ToInt32(textBox1.Text) / Convert.ToInt32(textBox2.Text)).ToString();
}
}
}
You can use the below Function, and add it for Key press event of the text box.
private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
Simplest way is to use the NumericUpDown control instead TextBox. NumericUpDown only allows numbers as their input and have similar properties of TextBox.
Access the value like this :
decimal answer=numericUpDown1.Value
`
Use NumericUpDown
You can find here a similar question How do I make a textbox that only accepts numbers?
make it simple try this
//function
public static void NumberOnly(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
//to call used this
NumberOnly("your textbox");

How I can bound a checkBox with KeyPress event of a textBox in C#

Hi I'm new in C# visual programming and I'm facing a problem in winform that is I want to make the textBox accepts numbers only when a checkBox is checked ... the problem is that I know how to use the code inside KeyPress event but it doesn't work with the idea of checkBox.
I have this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(char.IsLetter(e.Keychar))
{
e.Handled = true;
}
}
Now the question is how to make this happens when a checkBox is checked???
on your key press event you could do:
if (this.checkBoxNumericOnly.Checked)
{
//your code to only allow numerics...
}
Thanks to all of you ..
I wrote this code to enter numbers but only one dot '.' and it works finally ... thanks a lot for help
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (this.checkBox1.Checked)
{
e.Handled = !char.IsDigit(e.KeyChar)&&(e.KeyChar != '.') && !char.IsControl(e.KeyChar);
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
}
Use the MaskedTextBox control and handle the checkbox event to change the mask property
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if(checkBox1.Checked == true)
{
maskedTextBox1.Mask = "000-000-0000";
}
else
{
maskedTextBox1.Mask = null;
}
}
Simply try this in your TextBox's keypress event :
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(this.checkBox1.Checked)
{
//Allow only number
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
}

Select - Yes or No

I am making a yes or no comboBox labeled "comboBox". In my Items property of my yesnocomboBox, I put first item as Yes, and second item as No.
When I let my user select Yes, it has to show visibility to other certain labels and TextBoxs. How do I code to do that?
So far I have this and it isn't working:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(yesnocomboBox.SelectedItem = "0"){
}
}
Okay, I chose to use a checkbox instead. This is my code so far for when a user checks the checkbox:
private void yestochappedlipsCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (yestochappedlipsCheckBox.Checked = chapstickbrandsListBox.Visible = true)
(choosewhatyouwanttobuyLabel.Visible = true);
How do I make both of their visibilities to appear true?
private void yestochappedlipsCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (yestochappedlipsCheckBox.Checked)
{
chapstickbrandsListBox.Visible = true;
choosewhatyouwanttobuyLabel.Visible = true;
}
}
I see you said you were switching to a checkbox but to do it with a combo would be quite simple. I think you are using an assignment op in your code instead of an equal compare. Try the following by checking the index instead of the item.
Also, as good coding practice, keep your brackets consistent.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(yesnocomboBox.SelectedIndex == 0)
{
label1.Visible = true;
otherItem.Visible = true;
anotherItem.Visible = false;
}
}
If you're too serious to use that comboBox with Yes or No choices. make sure to set the DropDownStyle = DropDownList
bool? IsYes;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != -1)
{
//IsYes = comboBox1.SelectedIndex == 0;
choosewhatyouwanttobuyLabel.Visible = comboBox1.SelectedIndex == 0;
}
else
{
IsYes = null;
}
}

c# windows forms capital letters

My user can enter some text into the combobox but I wish that this text is automatically shown in capital letters (as if user had capslock on). Any ideas how to do this?
You will want to handle the KeyPress event.
private void ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= 'a' && e.KeyChar <= 'z')
e.KeyChar -= (char)32;
}
32 is just the difference in ASCII values between lowercase and uppercase letters.
Here is how I handled it, it gives a much smoother change than simply replacing the whole text.
private void ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsLetter(e.KeyChar))
{
int p = this.SelectionStart;
this.Text = this.Text.Insert(this.SelectionStart, Char.ToUpper(e.KeyChar).ToString());
this.SelectionStart = p + 1;
}
}
another example
private void TextBox_Validated(object sender, EventArgs e)
{
this.TextBox.Text = this.TextBox.Text.ToUpper();
}
Regards
You can register to the TextChanged event and convert the text to capitals.
private void combobox_TextChanged(object sender, EventArgs e)
{
string upper = combobox.Text.ToUpper();
if(upper != combobox.Text)
combobox.Text = upper;
}

Categories

Resources