Textbox validation 2 char and 2 integer - c#

i need to validate textbox1 as 2 alphabets and 2integer only i.e) ab11
how i can set it my text box only accept 2 chars and 2 integers.
Please help me...

if:
string myString = textbox1.Text;
Then to validate:
If (Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}$")))
{
return true;
}
else
{
return false;
}

private void textBox2_Validating(object sender, CancelEventArgs e)
{
var cn = textBox2.Text.Where(c => char.IsLetter(c)).Count();
var cd = textBox2.Text.Where(c => char.IsNumber(c)).Count();
if (cn >= 2 && cd >= 2)
{
//Success, Do Stuff
}
else
{
e.Cancel = true;
}
}

This should work.
private void textBox1_TextChanged(object sender, EventArgs e)
{
TextBox tb=sender as TextBox;
string text=tb.Text;
switch (text.Length)
{
case 1:
if (!char.IsLetter(text[0]))
tb.Text = "";
break;
case 2:
if (!char.IsLetter(text[1]))
tb.Text = text.Remove(1);
break;
case 3:
if (!char.IsNumber(text[2]))
tb.Text = text.Remove(2);
break;
case 4:
if (!char.IsNumber(text[3]))
tb.Text = text.Remove(3);
break;
default:
if(text.Length>4)
tb.Text = text.Substring(0, 4);
break;
}
textBox1.Select(tb.Text.Length, 0);
}

string str = textBox1.Text;
if (Regex.IsMatch(str, #"^(([A-Z]|[a-z])([A-Z]|[a-z])\d\d)$"))
{
MessageBox.Show("Valid");
}
Reference: Regex Class

Related

calculator equal button c#

I have a problem that I want to solve but I don't know how. I made a simple calculator with only a few buttons (Button 1, Button 5, Button+ and Button Equals). I want to make Button Equal repeat the last operation(in this case addition). It works fine when I press 5 + 1 and get the result 6, but after that, when I press Button Equal again, I don't get result 7 but I get 12.
I simply don't know where my mistake is and how to make that repeat function and without adding another button.
I hope someone replies soon and helps my problem. :)
string input = string.Empty;
string oper1 = string.Empty;
string oper2 = string.Empty;
char operacija;
double rezultat = 0.0;
bool rez = false;
bool repeating= false;
private void buttonNumber1_Click(object sender, RoutedEventArgs e)
{
this.textBoxPrikazi.Text = "";
if (rez)
{
input = "1";
rez = false;
}
else
{
input += "1";
}
this.textBoxPrikazi.Text += input;
}
private void buttonNumber5_Click(object sender, RoutedEventArgs e)
{
this.textBoxPrikazi.Text = "";
if (rez)
{
input = "5";
rez = false;
}
else
{
input += "5";
}
this.textBoxPrikazi.Text += input;
}
private void buttonPlus_Click(object sender, RoutedEventArgs e)
{
textBoxPrikazi.Text = "+";
oper1 = input;
operacija = '+';
input = string.Empty;
}
private void buttonEquals_Click(object sender, RoutedEventArgs e)
{
oper2 = input;
double num1, num2;
double.TryParse(oper1, out num1);
double.TryParse(oper2, out num2);
this.textBoxPrikazi.Text = "0";
this.input = string.Empty;
this.oper1 = string.Empty;
this.oper2 = string.Empty;
if (operacija == '+')
{
// x = 1 + 5
rezultat = num1 + num2;
textBoxPrikazi.Text = rezultat.ToString();
// for repeating
if (repeating== true)
{
// 6 = 6
rezultat = num2;
// 6+ 6 = 12
textBoxPrikazi.Text = (rezultat + num2).ToString();
repeating= false;
}
}
if (rezultat == 0)
{
textBoxPrikazi.Text = "0";
}
else
{
input = rezultat.ToString();
rez = true;
repeating= true; // for repeating
}
}
}

How can I find the last character of a textbox text?

I am a beginner in C#. I am making a web calculator like Microsoft Desktop calculator with the help of asp.net. But I'm stuck at one place. My code for Plus, minus, multiply or div is like:
protected void btnPlus_Click(object sender, EventArgs e)
{
if (txtBox1.Text.EndsWith("+"))
{
txtBox1.Text = txtBox1.Text;
}
else
{
txtBox1.Text = txtBox1.Text + "+";
ViewState["Operation"] = "+";
}
}
But I want to check this condition for all operations like minus, multiply and divide. I don't want Plus, Minus, Multiply or Div signs appear in the textbox.
You can store all your operators in a string constant and check if the last character is contained in that string:
private const string OPERATORS = "+-/*";
protected void btnPlus_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtBox1.Text) || // check if string is empty
OPERATORS.Contains(txtBox1.Text.Last())) // or if last character is a operator
{
txtBox1.Text = txtBox1.Text;
}
else
{
txtBox1.Text = txtBox1.Text + "+";
ViewState["Operation"] = "+";
}
}
You can do something like the following:
Extract last character
Based on the character assign operator to the view state
If it is any operator then remove them from the textbox
Finally do the operation
if (txtBox1.Text != "")
{
char last_char = txtBox1.Text[txtBox1.Text.Length - 1];
switch (last_char)
{
case '+':
ViewState["Operation"] = "+";
txtBox1.Text.Remove(txtBox1.Text.Length - 1);
break;
case '-':
ViewState["Operation"] = "-";
txtBox1.Text.Remove(txtBox1.Text.Length - 1);
break;
// do the same for all operators
default:
break;
}
}

Cannot calculate decimals in my calculator

So, I have made a calculator in C# but it cannot calculate decimal numbers.
It works perfectly fine when clicking on for example the buttons: 6 then . (this is a dot) then 5. But as soon as I click on the "+"-button (or any other operator) afterwards in the form, the program stops and I get a message saying that
"An unhandled exception of type 'System.FormatException' occured in
mscorlib.dll. The input string was not in a correct format".
I don't know exactly how to solve this. Is there anyone that knows how to solve this problem?
Here is my code:
namespace Kalkylator{
public partial class Form1 : Form{
String operation = ""; //the operation we will use
Double resultat = 0; //the result we will get
bool finished = false; //if false, we have not pressed the "=" button yet
public Form1(){
InitializeComponent();
}
//
private void button_click(object sender, EventArgs e){
if (finished == true){ //if we press any operator, clear the textbox-window so new numbers can be entered
textBoxFonster.Clear();
}
finished = false; //we are not done with the calculation
Button b = (Button)sender;
if (b.Text == "."){
if (!textBoxFonster.Text.Contains(".")){
textBoxFonster.Text = textBoxFonster.Text + b.Text;
}
}
else{
textBoxFonster.Text = textBoxFonster.Text + b.Text; //writes the number in the textBox
}
}
private void operator_click(object sender, EventArgs e)
{
Button b = (Button)sender;
operation = b.Text; //the operation we will perform is the operatorButton we will press
resultat = Double.Parse(textBoxFonster.Text); //HERE IS WHERE THE PROGRAM GIVES ME THE ERROR.
finished = true; //we are done with the calculation
}
private void clear_click(object sender, EventArgs e)
{
textBoxFonster.Text = ""; //clear the window from all text
resultat = 0; //clear the value of resultat and set it to 0
}
private void LikaMed_click(object sender, EventArgs e)
{
switch(operation){
case "+": //add the result with the text in the textBox
textBoxFonster.Text = (resultat + Double.Parse(textBoxFonster.Text)).ToString();
break;
case "-":
textBoxFonster.Text = (resultat - Double.Parse(textBoxFonster.Text)).ToString();
break;
case "*":
textBoxFonster.Text = (resultat * Double.Parse(textBoxFonster.Text)).ToString();
break;
case "%":
textBoxFonster.Text = (resultat / Double.Parse(textBoxFonster.Text) * (resultat/100)).ToString();
break;
case "^":
textBoxFonster.Text = (Math.Pow(resultat, Double.Parse(textBoxFonster.Text))).ToString();
break;
case "Log": //takes the 10th log of resultat
textBoxFonster.Text = (Math.Log10(resultat)).ToString();
break;
case "Sqrt":
textBoxFonster.Text = (Math.Sqrt(resultat)).ToString();
break;
case "/": //divide the result with the text in the textBox if that text is not 0. If so, show an error message
if ((Double.Parse(textBoxFonster.Text)) != 0){
textBoxFonster.Text = (resultat / Double.Parse(textBoxFonster.Text)).ToString();
}
else{ //show error in MessageBox
MessageBox.Show("Cannot divide by 0!");
}
break;
default:
break;
}
finished = true; //this will clear the result textbox when clicking another number after the equal sign has been clicked
}
}
}
Don't use Double.Parse without specifying the Culture.
Change:
switch(operation){
case "+": //add the result with the text in the textBox
textBoxFonster.Text = (resultat + Double.Parse(textBoxFonster.Text)).ToString();
break;
case "-":
textBoxFonster.Text = (resultat - Double.Parse(textBoxFonster.Text)).ToString();
break;
to:
Double operand1=resultat;
Double operand2=0;
Double.TryParse(textBoxFonster.Text,NumberStyles.Float,CultureInfo.InvariantCulture,out operand2);
switch(operation){
case "+": //add the result with the text in the textBox
textBoxFonster.Text = (operand1 + operand2).ToString();
break;
case "-":
textBoxFonster.Text = (operand1 - operand2).ToString();
break;
Alternatively, you could actually support multiple cultures, and change this code:
if (b.Text == "."){
if (!textBoxFonster.Text.Contains(".")){
textBoxFonster.Text = textBoxFonster.Text + b.Text;
}
}
to this:
if (b.Text == System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator){
if (!textBoxFonster.Text.Contains(System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator)){
textBoxFonster.Text = textBoxFonster.Text + b.Text;
}
}

Automatic cell format to money

I try to make a automatic format system for money, for example: to digit the number 5124.25
the user types 5: 0,05
the user types 1: 0,51
the user types 2: 5,12
the user types 4: 51,24
the user types 2: 512,42
the user types 5: 5124,25
I need to put this "format style" in one column of datagridview, for this, I try this:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var temp = (DataGridView)sender;
if (temp.CurrentCell.ColumnIndex == 4)
{
e.Control.PreviewKeyDown -= Control_PreviewKeyDown;
e.Control.PreviewKeyDown += new PreviewKeyDownEventHandler(Control_PreviewKeyDown);
}
}
void Control_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
var temp = (DataGridViewTextBoxEditingControl)sender;
TextBoxMoeda(ref temp, e);
/*if (e.KeyCode == Keys.Escape)
{
System.Diagnostics.Debug.Print("escape pressed");
}*/
}
public static void TextBoxMoeda(ref DataGridViewTextBoxEditingControl txt, PreviewKeyDownEventArgs e)
{
string n = string.Empty;
double v = 0;
try
{
n = txt.Text.Replace(",", "").Replace(".", "").Replace("R$", "");
if (n.Length == 0)
txt.Text = "0,00";
else if (n.Length == 1)
txt.Text = "0,0" + n;
else if (n.Length == 2)
txt.Text = "0," + n;
else if(n.Length > 2)
txt.Text = n.Substring(0, n.Length - 2) + "," +
n.Substring(n.Length - 2);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "TextBoxMoeda");
}
}
How It's possible to make this dinamic format for money ?
Try setting the DefaultCellStyle.Format to "c" for money or whatever format you want, and then subscribe to the CellFormatting event:
dataGridView1.Columns["Column2"].DefaultCellStyle.Format = "c";
dataGridView1.CellFormatting += dataGridView1_CellFormatting;
Try parsing the information into a decimal for your formatting:
void dataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e) {
if (e.CellStyle.Format == "c" &&
e.RowIndex != this.dataGridView1.NewRowIndex) {
decimal d;
if (e.Value != null && decimal.TryParse(e.Value.ToString(), out d)) {
e.Value = d.ToString("c");
}
}
}

Increment the number by 1

I would like to see label6 display the number of correct times the user chooses the number. And label7 display the number of times the user choose incorrectly. Its not incrementing by one.
Error 1 Operator '++' cannot be applied to operand of type 'string'
Error 2 Operator '++' cannot be applied to operand of type 'string'
private void button1_Click(object sender, EventArgs e)
{
string correct="0";
string incorrect="0";
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
label3.Text=("Winner");
label6.Text = correct +1;
if (textBox1.Text != label1.Text)
label7.Text = incorrect= +1;
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
}
Edit (From OP's answer to his own question):
I have tried the ways your suggesting but the number doesnt increase by one everytime I guess wrong.
private void button1_Click(object sender, EventArgs e)
{
int correct=0;
int incorrect=0;
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text = ("Winner");
label6.Text = (++correct).ToString();
}
else if (textBox1.Text != label1.Text)
{
label7.Text = (incorrect+1).ToString();
label3.Text = (string.Format("Sorry - You Lose, The number is {0}", label1.Text));
}
}
It doesn't look like you're persisting the correct and incorrect
Create Properties:
public int Correct { get; set; }
public int Incorrect { get; set;}
Then:
private void button1_Click(object sender, EventArgs e)
{
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text=("Winner");
label6.Text = (++this.Correct).ToString();
}
else
{
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
label7.Text = (++this.Incorrect).ToString();
}
}
You are storing your correct and incorrect variables as string.
Use int instead like this:
int correct = 0;
int incorrect = 0;
and change your code to:
correct++;
label6.Text = correct.ToString();
and:
incorrect++;
label7.Text = incorrect.ToString();
Adding to strings, correct and incorrect will just append the string representation of what's added. You have to convert it to an integer type, then increment, then convert back to string. However it would be easier to just keep these variables as integer instance variables. That way incrementing is trivial and you are actually keeping the correct count and not resetting every time the button gets clicked. (There are actually a number of problems with the code)
// instance variables
private int correct = 0;
private int incorrect = 0;
private void button1_Click(object sender, EventArgs e)
{
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text=("Winner");
label6.Text = (++correct).ToString(); // convert int to string
}
// indentation does not indicate the block
else //if (textBox1.Text != label1.Text)
{
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
label7.Text = (++incorrect).ToString();
}
}
Or you can use:
correct = correct + 1; ( I think this is what you were trying to achieve)
incorrect = incorrect + 1;
OR
correct += 1;
incorect += 1;
label6.Text = correct +1;
only sets label6's value to correct + 1; it does not change the value of correct. If you use:
int correct;
label6.Text = (++correct).ToString();
you should see what you want.

Categories