Checkbox self checking C# - c#

Here is my problem and yes I am a newbie
I have a form (dialog) that has two checkboxes (chbxAlpha and chbxBravo), two textboxes (tbxAlpha and tbxBravo) which can only receive 6 char , and two buttons (Submit and Cancel)
The form is loaded by an error event
When the form is loaded if Alpha is the error then I will check Alpha Checkbox and then fill in the error in Alpha Textbox
If chars are < > than 6 a messagebox appears alerting the user that they must submit 6 chars no more and no less
When I press the submit button the form then automatically checks Bravo Checkbox and I have to fill it out even there has been no error
I cannot figure out why
Below is the code
private void btnSubmit_Click(object sender, EventArgs e)
{
if (chbxAlpha.Checked = true && tbxAlpha.Text.Length != 6)
{
MessageBox.Show("A valid entry requires 6 digits. Please use forward zeros if data is less than 6 digits eg 1234 = 001234.Thankyou");
tbxAlpha.Text = "";
tbxAlpha.Focus();
}
else
{
this.DialogResult = DialogResult.OK;
}
if (chbxBravo.Checked = true && tbxBravo.Text.Length != 6)
{
MessageBox.Show("A valid entry requires 6 digits. Please use forward zeros if data is less than 6 digits eg 1234 = 001234.Thankyou");
tbxBravo.Text = "";
tbxBravo.Focus();
}
else
{
this.DialogResult = DialogResult.OK;
}
}
private void chbxBravo_CheckedChanged(object sender, EventArgs e)
{
if (chbxBravo.Checked == true)
{
tbxBravo.Visible = true;
tbxBravo.Focus();
}
}
private void chbxAlpha_CheckedChanged(object sender, EventArgs e)
{
if (chbxAlpha.Checked == true)
{
tbxAlpha.Visible = true;
tbxAlpha.Focus();
}
}
}
}
The other question I have is how can I prevent Null char from being used eg. 123space56
Appreciate any help
JJ

It looks like you are using an assignment operator rather than an equality operator in both your if statements in btnSubmit_click function.
In answer to your second question, you can use a Regex to check that all 6 characters are digits.
private void btnSubmit_Click(object sender, EventArgs e)
{
Regex regexIs6Digits = new Regex(#"^\d{6}$");
if (chbxAlpha.Checked && !regexIs6Digits.IsMatch(tbxAlpha.Text))
{
MessageBox.Show("A valid entry requires 6 digits. Please use forward zeros if data is less than 6 digits eg 1234 = 001234.Thankyou");
tbxAlpha.Text = "";
tbxAlpha.Focus();
}
else
{
this.DialogResult = DialogResult.OK;
}
if (chbxBravo.Checked && !regexIs6Digits.IsMatch(tbxBravo.Text))
{
MessageBox.Show("A valid entry requires 6 digits. Please use forward zeros if data is less than 6 digits eg 1234 = 001234.Thankyou");
tbxBravo.Text = "";
tbxBravo.Focus();
}
else
{
this.DialogResult = DialogResult.OK;
}
}

Related

If-statement error: "cannot convert type 'string' to 'bool'" [duplicate]

This question already has answers here:
Why do assignment statements return a value?
(14 answers)
Closed 4 years ago.
I'm trying to display a Button called track with the text: "Start". But when I click the button I want to change the text to "Stop". Well, that's not much of a problem, but I want to change the text back in the "Start" when I press the button again. And over and over.
I already tried with an if-statement and using null, but that doesn't work. Also, the options when pressing alt+enter do not seem to work.
protected void change(object sender, EventArgs ea)
{
if (track.Text == "Track")
{
track.Text = "Track";
}
else
{
track.Text = "Stop";
}
}
Should be if (track.Text == "Start"), not single =.
You are attempting to do exactly what the errors says. Instead of if (track.Text = "Start" , it should be if (track.Text == "Start") :
protected void changetext(object sender, EventArgs e)
{
if (track.Text == "Start")
{
track.Text = "Start";
status.Text = "Je staat stil";
}
else
{
track.Text = "Stop";
status.Text = "Je bent in beweging. Ga zo door!";
}
}
After OP's edit:
protected void change(object sender, EventArgs ea)
{
if (track.Text == "Track")
{
track.Text = "Track";
}
else
{
track.Text = "Stop";
}
}
In other languages the test if (track.Text = "Start") is nearly always a typo.
C# only allows bool for comparison, to virtually eliminate the risk of a typo leading to a bug.
The only possible mistake remaining is if you have something like this :
Bool a = true;
Bool b = false;
If(a = b){
//this is true
}
Next time pay attention to that, you wan’t to compare two values, not the result of an affectation.

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 = "";
}
}
}
}

Detect decimal separator

I have to detect decimal separator in current windows setting. Im using visual studio 2010, windows form. In particular, if DecimalSeparator is comma, if user input dot in textbox1, I need show zero in textbox2.
I tryed with this code, but not works:
private void tbxDaConvertire_KeyPress(object sender, KeyPressEventArgs e)
{
string uiSep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;
if (uiSep.Equals(","))
{
while (e.KeyChar == (char)46)
{
tbxConvertito.Text = "0";
}
}
}
I have tryed also this code, but not work:
private void tbxDaConvertire_KeyPress(object sender, KeyPressEventArgs e)
{
string uiSep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
if (uiSep.Equals(","))
{
if (e.KeyChar == (char)46)
{
tbxConvertito.Text = "0";
}
}
}
Solution:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char a = Convert.ToChar(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (e.KeyChar == a)
{
e.Handled = true;
textBox1.Text = "0";
}
}
That way, when you hit . or , you will have a 0 in your TextBox.
EDIT:
If you want to insert a 0 everytime you hit the decimal separator, this is the code:
char a = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (e.KeyChar == a)
{
e.KeyChar = '0';
}
Actually you should be using
CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
instead of
CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator
Using the second one gives you the OS default settings, which might be different then user Regional Locales for particular user account logged to this PC.
Credits to berhir and Grimm for pointing out the [docs]
You shouldn't use a while loop, I think it will freeze the application, use if instead, the problem might be here

Error provider checked number of digits of input textbox

I used from Error Provider in C# winform. in my form have textbox. error provider checked it that it contain two number. it means that input is digit and number of digit is two number. when input is 2 char , error provider is worked but when input is char and digit, error provider didn't worked.
please check my code.
private void textbox1_Leave(object sender, EventArgs e)
{
string text = textbox1.Text;
bool hasDigit = false;
foreach (char letter in text)
{
if (char.IsDigit(letter))
{
hasDigit = true;
break;
}
}
// Call SetError or Clear on the ErrorProvider.
if (!hasDigit )
{
errorProvider1.SetError(textbox1, "Please enter digit");
}
else if(hasDigit)
{
if (text.TextLength != 2)
{
errorProvider1.SetError(textbox1, "Number of digit is two number");
}
else
errorProvider1.Clear();
}
}
So you want to ensure that all chars are digits. But you're checking only the first, if that's a digit you're breaking the loop:
foreach (char letter in text)
{
if (char.IsDigit(letter))
{
hasDigit = true;
break;
}
}
Instead you could use Linq for this. Enumerable.All is made for this purpose:
bool allDigits = text.All(c => Char.IsDigit(c));
(but maybe i'm totally off the track since the question is not so clear imho)

To Disable Negative Values Inside a TextBox

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

Categories

Resources