Allow only one decimal point in a Text Box - c#

I am designing a basic calculator using C#. I am facing difficulties while I am entering a decimal point. Example, if I am entering .8 then it gives me 0.8 which is correct if there is nothing on the display screen but after that if I am entering the decimal symbol, then also it accepts it that is 0.8..... I want only one decimal symbol to be accepted for one number. My code is
private void btn_Decimal_Click(object sender, EventArgs e)
{
if (txt_Result.Text == "" || LastcharIssymbol==true)
{
txt_Result.Text = txt_Result.Text + 0 + ".";
}
else
txt_Result.Text = txt_Result.Text + ".";
}
Here, if I am entering 0.9.999 then also it accepts and if I am entering 999..... then also it accepts. I want only one decimal symbol to be accepted for one number that is 999.999. Please help me. Also I am adding two additional labels that can show the current system date and time. I am unable to show the date as well as the time but I am able to show the date and time using VB.Net. I don't know where I am getting the errors. My whole code is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CS_Calculator
{
public partial class Form1 : Form
{
Boolean LastcharIssymbol {get;set;}
string op;
double a, memory;
public Form1()
{
InitializeComponent();
}
private void btn_1_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "1";
LastcharIssymbol= false;
}
private void btn_2_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "2";
LastcharIssymbol = false;
}
private void btn_3_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "3";
LastcharIssymbol = false;
}
private void btn_4_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "4";
LastcharIssymbol = false;
}
private void btn_5_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "5";
LastcharIssymbol = false;
}
private void btn_6_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "6";
LastcharIssymbol = false;
}
private void btn_7_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "7";
LastcharIssymbol = false;
}
private void btn_8_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "8";
LastcharIssymbol = false;
}
private void btn_9_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "9";
LastcharIssymbol = false;
}
private void btn_0_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "0";
LastcharIssymbol = false;
}
private void btn_Decimal_Click(object sender, EventArgs e)
{
if (txt_Result.Text == "" || LastcharIssymbol==true)
{
txt_Result.Text = txt_Result.Text + 0 + ".";
}
else
txt_Result.Text = txt_Result.Text + ".";
}
private void btn_Plus_Click(object sender, EventArgs e)
{
if(txt_Result.Text=="" || LastcharIssymbol)
{
MessageBox.Show("Please Enter first number to perform the addition operation.");
}
else
{
op = "+";
txt_Result.Text = txt_Result.Text + op;
LastcharIssymbol=true;
}
}
private void btn_Minus_Click(object sender, EventArgs e)
{
if (txt_Result.Text == "" || LastcharIssymbol)
{
MessageBox.Show("Please enter first number to erform the substraction operation.");
}
else
{
op = "-";
txt_Result.Text = txt_Result.Text + op;
LastcharIssymbol = true;
}
}
private void btn_Division_Click(object sender, EventArgs e)
{
if (txt_Result.Text == "" || LastcharIssymbol)
{
MessageBox.Show("Please enter first number to perform the division operation.");
}
else
{
op = "/";
txt_Result.Text = txt_Result.Text + op;
LastcharIssymbol = true;
}
}
private void btn_Mult_Click(object sender, EventArgs e)
{
if (txt_Result.Text == "" || LastcharIssymbol)
{
MessageBox.Show("Please enter first number to perform the multiplication operation.");
}
else
{
op = "*";
txt_Result.Text = txt_Result.Text + op;
LastcharIssymbol = true;
}
}
private void btn_Equal_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
txt_Result.Text = "";
}
private void btn_Clear_All_Click(object sender, EventArgs e)
{
txt_Result.Text = "";
op = "";
a = 0;
memory = 0;
}
private void btn_Memory_Click(object sender, EventArgs e)
{
memory = Convert.ToDouble(txt_Result.Text);
}
private void btn_Show_Memory_Click(object sender, EventArgs e)
{
txt_Result.Text = memory.ToString();
}
}
}

You should disable the decimal once it is clicked and enable it again if any of the operator or 'C' is pressed.

if (!txt_Result.Text.Contains("."))
if(txt_Result.Text == string.Empty)
txt_Result.Text = "0.";
else
txt_Result.Text += ".";
else
MessageBox.Show("more dots are not allowd");
for the case you have text like '11.9+12' which has operations in it you can do the following
string formula = "11.9/1.2*99.9+19";
string lastPiece = formula.Split(new char[] { '+', '-', '*', '/' })[formula.Split(new char[] { '+', '-', '*', '/' }).Count() - 1];
if (!lastPiece.Contains('.')) formula += ".";
//adds dot
lastPiece = formula.Split(new char[] { '+', '-', '*', '/' })[formula.Split(new char[] { '+', '-', '*', '/' }).Count() - 1];
if (!lastPiece.Contains('.')) formula += ".";
//does not add dot
MessageBox.Show(formula);
//output : 11.9/1.2*99.9+19.

You could use decimal.TryParse to test whether the string is a valid decimal number. If not, such as if your input has two decimal points, then the TryParse call fails.
TryParse is a good option because there can be many issues with an entered number besides a doubled decimal point such as... a triple decimal point, a misplaced minus sign, alpha chars etc.
Try:
private void btn_Decimal_Click(object sender, EventArgs e)
{
decimal num;
if (!Decimal.TryParse(txt_Result.Text, out num))
{
MessageBox.Show(txt_Result.Text + " is not a valid number.");
return;
}
if (txt_Result.Text == "" || LastcharIssymbol==true)
txt_Result.Text = txt_Result.Text + 0 + ".";
else
txt_Result.Text = txt_Result.Text + ".";
}

private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)//textprice key pressed
{
if ((e.KeyChar < '0' || e.KeyChar > '9') && (e.KeyChar != '\b') && (e.KeyChar != '.'))
{
e.Handled = true;
}
else
{
e.Handled = false;
}
if (Char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else if (Char.IsNumber(e.KeyChar) || e.KeyChar == '.')
{
TextBox tb = sender as TextBox;
int cursorPosLeft = tb.SelectionStart;
int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
string result = tb.Text.Substring(0, cursorPosLeft) + e.KeyChar + tb.Text.Substring(cursorPosRight);
string[] parts = result.Split('.');
if (parts.Length > 1)
{
if (parts[1].Length > 2 || parts.Length > 2)
{
e.Handled = true;
}
}
}

Change your last else to:
else if (!txt_Result.Text.Contains (".")) {
txt_Result.Text = txt_Result.Text + ".";
}
Or consider disabling the decimal point button.
You should probably do some validation on the value to ensure it is a valid number.

**Another example , 100% **
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtPrice.Text.Length == 0)
{
if (e.KeyChar == '.')
{
e.Handled = true;
}
}
if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 46)
{
e.Handled = true;
}
if (e.KeyChar == '.' && txtPrice.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}

This works for me:
if (!txt_Result.Text.Contains("."))
if(txt_Result.Text == string.Empty)
txt_Result.Text = "0.";
else
MessageBox.Show("Sorry, invalid number format!
Value can't have more than a decimal point");
else
txt_Result.Text += ".";

Put this code in textbox_keypress
here txtweight is my textbox name you use yours
private void txtweight_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtweight.Text.Length == 0)
{
if (e.KeyChar == '.')
{
e.Handled = true;
}
}
if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 46)
{
e.Handled = true;
}
if (e.KeyChar == '.' && txtweight.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}

Related

How to allow the user to only edit the current line and not the previous lines above in the textBox

Here is a picture of when I run the program. I want the user to be able to only type on the current line. They shouldn't be able to edit the lines above.
Here is the link to the github if you want to downlaod it to use it for yourself. https://github.com/TeddyRoche/Calculator
Here is the code that is controlling the whole program.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Calculator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
float number_Initial = 0;
float prev_Answer = 0;
List<float> number_List = new List<float>();
List<string> equations = new List<string>();
bool valid = true;
int key_Press = 0;
int maxLines = 0;
string lastLine = "";
public MainWindow()
{
InitializeComponent();
}
private void NumPressedButton(int i)
{
if (valid == false)
{
MessageBox.Show("Please enter only numbers.");
displayText.Text = displayText.Text.Remove(displayText.Text.Length - 1);
}
else
{
if (key_Press < 12)
{
this.displayText.Text += i;
number_Initial = number_Initial * 10 + i;
key_Press++;
}
}
valid = true;
}
private void NumPressedKeyboard(int i)
{
if (valid == false)
{
MessageBox.Show("Please enter only numbers.");
displayText.Text = displayText.Text.Remove(displayText.Text.Length - 1);
}
else
{
if (key_Press < 12)
{
number_Initial = number_Initial * 10 + i;
key_Press++;
}
}
valid = true;
}
private void OutputSymbol(string x)
{
switch (x)
{
case "+":
equations.Add("add");
break;
case "-":
equations.Add("sub");
break;
case "*":
equations.Add("mul");
break;
case "/":
equations.Add("div");
break;
}
}
private void SymbolPressedButton(String x)
{
if (lastLine == "")
{
this.displayText.AppendText("Ans");
number_List.Add(prev_Answer);
this.displayText.AppendText(x);
OutputSymbol(x);
key_Press = key_Press + 4;
}
else
{
if (number_Initial == 0)
{
this.displayText.AppendText(x);
OutputSymbol(x);
key_Press++;
}
else
{
number_List.Add(number_Initial);
this.displayText.AppendText(x);
OutputSymbol(x);
number_Initial = 0;
key_Press++;
}
}
}
private void SymbolPressedKeyboard(String x)
{
if (lastLine == "")
{
this.displayText.AppendText("Ans");
number_List.Add(prev_Answer);
OutputSymbol(x);
key_Press = key_Press + 4;
}
else
{
if (number_Initial == 0)
{
OutputSymbol(x);
key_Press++;
}
else
{
number_List.Add(number_Initial);
OutputSymbol(x);
number_Initial = 0;
key_Press++;
}
}
}
//Display____________________________________________________________________________________________________________________________________________________
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
maxLines = displayText.LineCount;
if(maxLines > 0)
{
lastLine = displayText.GetLineText(maxLines - 1);
}
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
//check to see if what the user presses is a number or one of the appropriate symbols allowed
//if not sets valid to false
valid = true;
if(e.Key < Key.D0 || e.Key > Key.D9)
{
if(e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
{
valid = false;
if (e.Key == Key.Add || e.Key == Key.Subtract || e.Key == Key.Multiply || e.Key == Key.Divide || e.Key == Key.Enter)
{
valid = true;
}
}
}
if(valid == true)
{
//Performing functions when a certain key is pressed
switch (e.Key)
{
case Key.NumPad0:
case Key.D0:
NumPressedKeyboard(0);
break;
case Key.NumPad1:
case Key.D1:
NumPressedKeyboard(1);
break;
case Key.NumPad2:
case Key.D2:
NumPressedKeyboard(2);
break;
case Key.NumPad3:
case Key.D3:
NumPressedKeyboard(3);
break;
case Key.NumPad4:
case Key.D4:
NumPressedKeyboard(4);
break;
case Key.NumPad5:
case Key.D5:
NumPressedKeyboard(5);
break;
case Key.NumPad6:
case Key.D6:
NumPressedKeyboard(6);
break;
case Key.NumPad7:
case Key.D7:
NumPressedKeyboard(7);
break;
case Key.NumPad8:
case Key.D8:
NumPressedKeyboard(8);
break;
case Key.NumPad9:
case Key.D9:
NumPressedKeyboard(9);
break;
case Key.Add:
SymbolPressedKeyboard("+");
break;
case Key.Subtract:
SymbolPressedKeyboard("-");
break;
case Key.Divide:
SymbolPressedKeyboard("/");
break;
case Key.Multiply:
SymbolPressedKeyboard("*");
break;
case Key.Enter:
Equals_Equation();
break;
}
}
else if(valid == false)
{
MessageBox.Show("Please enter only numbers.");
//displayText.Text = displayText.Text.Remove(displayText.Text.Length - 1);
}
}
//Display____________________________________________________________________________________________________________________________________________________
//Numbers ___________________________________________________________________________________________________________________________________________________
private void _0_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(0);
}
private void _1_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(1);
}
private void _2_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(2);
}
private void _3_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(3);
}
private void _4_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(4);
}
private void _5_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(5);
}
private void _6_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(6);
}
private void _7_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(7);
}
private void _8_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(8);
}
private void _9_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(9);
}
//Numbers____________________________________________________________________________________________________________________________________________________
//Equations__________________________________________________________________________________________________________________________________________________
private void Divide_Click(object sender, RoutedEventArgs e)
{
SymbolPressedButton("/");
}
private void Multiply_Click(object sender, RoutedEventArgs e)
{
SymbolPressedButton("*");
}
private void Subtract_Click(object sender, RoutedEventArgs e)
{
SymbolPressedButton("-");
}
private void Add__Click(object sender, RoutedEventArgs e)
{
SymbolPressedButton("+");
}
protected void Equals_Equation()
{
if(equations.Count != 0)
{
if(this.displayText.Text.StartsWith("1") || this.displayText.Text.StartsWith("2") || this.displayText.Text.StartsWith("3") || this.displayText.Text.StartsWith("4") || this.displayText.Text.StartsWith("5") || this.displayText.Text.StartsWith("6") || this.displayText.Text.StartsWith("7") || this.displayText.Text.StartsWith("8") || this.displayText.Text.StartsWith("9") || this.displayText.Text.StartsWith("0"))
{
number_List.Add(number_Initial);
this.displayText.AppendText("\n");
//loop that goes through the equations list and does the appropriate calculations
//Does Multiplication and Division first
for (int s = 0; s < equations.Count(); s++)
{
if (equations[s] == "mul")
{
number_List[s] = number_List[s] * number_List[s + 1];
}
else if (equations[s] == "div")
{
number_List[s] = number_List[s] / number_List[s + 1];
}
}
//Then does Addition and Subtraction next
for (int s = 0; s < equations.Count(); s++)
{
if (equations[s] == "add")
{
number_List[0] = number_List[0] + number_List[s + 1];
}
else if (equations[s] == "sub")
{
number_List[0] = number_List[0] - number_List[s + 1];
}
}
//changes the display to show the answer and creates a new line for the user to continue
this.displayText.Text += number_List[0];
number_Initial = number_List[0];
number_List.Clear();
prev_Answer = number_Initial;
//number_List.Add(number_Initial);
number_Initial = 0;
equations.Clear();
this.displayText.AppendText("\n");
this.displayText.PageDown();
displayText.Select(displayText.Text.Length, 0);
}
else if (this.displayText.Text.StartsWith("A"))
{
number_List.Insert(0, prev_Answer);
number_List.Add(number_Initial);
this.displayText.AppendText("\n");
//loop that goes through the equations list and does the appropriate calculations
//Does Multiplication and Division first
for (int s = 0; s < equations.Count(); s++)
{
if (equations[s] == "mul")
{
number_List[s] = number_List[s] * number_List[s + 1];
}
else if (equations[s] == "div")
{
number_List[s] = number_List[s] / number_List[s + 1];
}
}
//Then does Addition and Subtraction next
for (int s = 0; s < equations.Count(); s++)
{
if (equations[s] == "add")
{
number_List[0] = number_List[0] + number_List[s + 1];
}
else if (equations[s] == "sub")
{
number_List[0] = number_List[0] - number_List[s + 1];
}
}
//changes the display to show the answer and creates a new line for the user to continue
this.displayText.Text += number_List[0];
number_Initial = number_List[0];
number_List.Clear();
prev_Answer = number_Initial;
//number_List.Add(number_Initial);
number_Initial = 0;
equations.Clear();
this.displayText.AppendText("\n");
this.displayText.PageDown();
displayText.Select(displayText.Text.Length, 0);
}
}
else
{
}
key_Press = 0;
}
private void Equals_Click(object sender, RoutedEventArgs e)
{
Equals_Equation();
}
//Clears all stored data so the user can start from scratch
private void Clear_Click(object sender, RoutedEventArgs e)
{
number_List.Clear();
number_Initial = 0;
equations.Clear();
this.displayText.Clear();
key_Press = 0;
}
//Equations__________________________________________________________________________________________________________________________________________________
}
}
I havent found much that has helped with only allowing the user to edit the current line. I see a lot with not allowing the user to edit the whole textBox.
I want the user to only be able to edit the current line. Right know I can use the arrow keys or click with my mouse on the previous lines and can edit them and I dont want them to be allowed to do this.
Here is a quick example. Hopefully this gives you enough info.
XAML
<TextBox
AcceptsReturn="True"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto"
PreviewTextInput="TextBox_PreviewTextInput"/>
Code Behind
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (sender is not TextBox box) //semi-redundant safety check
return;
//make sure there is text, also make sure there is a newline in the box
if (string.IsNullOrEmpty(box.Text) || (!box.Text.Contains('\n') && !box.Text.Contains('\r')))
return;
//through some testing I found the \r would be there without a \n so I include both for completeness
var lastReturn = Math.Max(box.Text.LastIndexOf('\r'), box.Text.LastIndexOf('\n'));
if (box.CaretIndex <= lastReturn)
e.Handled = true;
}
This solution can be expanded on, but it mainly prevents the Text from changing whenever Text is entered on any line but the last. I like it as you can also move the Text Caret around to get standard functionality still (highlighting, selection, etc.)

C# Calculator Logic

when I press 9 and then press times the display shows 9 and when I press 9 again it'll add it to the first number (9) instead of clearing the first 9. so it thinks its 9*99. how do I clear the display on the first input after an operation?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
string input = string.Empty;
string operand1 = string.Empty;
string operand2 = string.Empty;
char operation;
double result = 0.0;
public Form1()
{
InitializeComponent();
}
private void Multiply_Click(object sender, EventArgs e)
{
operation = '*';
if (operand1 != "")
{
calculate();
}
else
{
operand1 = input;
}
}
private void Minus_Click(object sender, EventArgs e)
{
operation = '-';
if (operand1 != "")
{
calculate();
}
else
{
operand1 = input;
}
}
private void Addition_Click(object sender, EventArgs e)
{
operation = '+';
if (operand1 != "")
{
calculate();
}
else
{
operand1 = input;
}
}
private void Divide_Click(object sender, EventArgs e)
{
operation = '/';
if (operand1 != "")
{
calculate();
}
else
{
operand1 = input;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void five_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
input += "5";
this.textBox1.Text += input;
}
private void Zero_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
input += "0";
this.textBox1.Text += input;
}
private void one_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
input += "1";
this.textBox1.Text += input;
}
private void two_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
input += "2";
this.textBox1.Text += input;
}
private void three_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
input += "3";
this.textBox1.Text += input;
}
private void four_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
input += "4";
this.textBox1.Text += input;
}
private void six_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
input += "6";
this.textBox1.Text += input;
}
private void seven_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
input += "7";
this.textBox1.Text += input;
}
private void eight_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
input += "8";
this.textBox1.Text += input;
}
private void nine_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
input += "9";
this.textBox1.Text += input;
}
private void Equal_Click(object sender, EventArgs e)
{
calculate();
}
private void Decimal_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
input += ".";
this.textBox1.Text += input;
}
private void Clear_Click(object sender, EventArgs e)
{
textBox1.Clear();
}
public void calculate()
{
Console.WriteLine("performing operation" + operand1 + " " + operation + " " + operand2 + "= ???" + "the input is?" + input);
operand2 = input;
double num1, num2;
double.TryParse(operand1, out num1);
double.TryParse(operand2, out num2);
if (operation == '*')
{
result = num1 * num2;
}
if (operation == '-')
{
result = num1 * num2;
}
if (operation == '+')
{
result = num1 * num2;
}
if (operation == '/')
{
result = num1 * num2;
}
textBox1.Text = result.ToString();
input = result.ToString();
}
}
}
Add the following to your class Form1:
bool operationExcecuted = false;
And in your calculate method add the following line:
operationExcecuted = true;
And in every number input check if an operation is excecuted. If so clear the input and add a new number. For example the number 9:
private void nine_Click(object sender, EventArgs e)
{
if(operationExcecuted)
{
input = String.Empty;
operationExcecuted = false;
}
this.textBox1.Text = "";
input += "9";
this.textBox1.Text += input;
}
I think, that's because of you adding
input += "9"
this.textBox1.text += input;
You're always adding the 9 to the variable input. Try cleaning input. Before adding a new number.

Double result when using keypress

I made this calculator in C# and I have one problem: When I press keyboard something like 1 it gives me incorrect result double number. I don't get the correct result.
Do you know what I am doing wrong,
Thank you very much!
namespace Calculator
{
public partial class Calculator : Form
{
Double value = 0;
String operation = "";
int i = 0;
bool operation_pressed = false;
bool button_dot = false;
OperationClass class1 = new OperationClass();
public Calculator()
{
InitializeComponent();
this.KeyPreview = true;
this.KeyPress += new KeyPressEventHandler(Calculator_KeyPress);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Calculator_Load(object sender, EventArgs e)
{
}
private void Calculator_KeyPress(object sender, KeyPressEventArgs e)
{
if ((result.Text == "0") || (operation_pressed))
result.Clear();
switch (e.KeyChar)
{
// key press from 0-9
case (char)48:
case (char)49:
case (char)50:
case (char)51:
case (char)52:
case (char)53:
case (char)54:
case (char)55:
case (char)56:
case (char)57:
e.Handled = true;
result.Text += e.KeyChar.ToString();
break;
}
}
private void button_Click(object sender, EventArgs e)
{
if ((result.Text == "0") || (operation_pressed))
result.Clear();
operation_pressed = false;
Button b = (Button)sender;
result.Text = result.Text + b.Text;
}
private void operator_click(object sender, EventArgs e)
{
Button b = (Button)sender;
operation = b.Text;
value = Double.Parse(result.Text);
operation_pressed = true;
equation.Text = value + " " + operation;
}
private void buttonCE_Click(object sender, EventArgs e)
{
result.Text = "0";
equation.Text = "";
button_dot = false;
}
private void buttonC_Click(object sender, EventArgs e)
{
result.Clear();
value = 0;
}
private void buttonEqual_Click(object sender, EventArgs e)
{
equation.Text = "";
button_dot = false;
operation_pressed = true;
if (operation != "")
result.Text = class1.GetResult(operation, value, result.Text);
else
result.Text = result.Text + "";
}
private void buttonDot_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if ((!button_dot && !operation_pressed) || result.Text == "0")
result.Text = result.Text + b.Text;
button_dot = true;
}
}
}
You don't need to append keychar in your result.Text (Assuming result is your TextBox item) as you have written in line result.Text += e.KeyChar.ToString();. That's the line which is doubling your input.
Remove it and it'll work as expected.
I'd change it from keypress to KeyUp instead. That way it only fires as soon as the key is released.
Edit: Check out this info: Difference between the KeyDown Event, KeyPress Event and KeyUp Event in Visual Studio

how to convert from double with decimal point number to binary in c# visual studio

i'm wrtting a code in visual studio c# that converts integers from binary to decimal mode and from decimal mode to binary but i want it to converts numbers with decimal points from decimal mode to binary how can i do this please help me and tell me what modifies i must put in my code
this is my code for the calculator :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace assignment2
{
public partial class Form1 : Form
{
const int asciiDiff = 48;
double num1 = 0, num2 = 0, result = 0;
double fact = 1;
int[] iHexaNumeric = new int[] { 10, 11, 12, 13, 14, 15 };
char[] cHexa = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
String a = "";
char op;
bool b = false;
const int base10 = 10;
public Form1()
{
//
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "1";
}
private void buttonTow_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "2";
}
private void buttonThree_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "3";
}
private void buttonFour_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "4";
}
private void buttonFive_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "5";
}
private void buttonSix_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "6";
}
private void buttonSeven_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "7";
}
private void buttonEight_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "8";
}
private void buttonNine_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "9";
}
private void buttonZero_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "0";
}
private void buttonPlus_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(DisplayResult.Text.ToString());
op = '+';
DisplayResult.Text = string.Empty;
}
private void buttonMinus_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(DisplayResult.Text.ToString());
op = '-';
DisplayResult.Text = string.Empty;
}
private void buttonMultipler_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(DisplayResult.Text.ToString());
op = '*';
DisplayResult.Text = string.Empty;
}
private void buttonDivider_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(DisplayResult.Text.ToString());
op = '/';
DisplayResult.Text = string.Empty;
}
private void buttonEqual_Click(object sender, EventArgs e)
{
if (DisplayResult.Text == "")
return;
else
{
try
{
num2 = Convert.ToDouble(DisplayResult.Text.ToString());
switch (op)
{
case '+': //suma
result = (num1 + num2);
DisplayResult.Text = result.ToString();
break;
case '-': //resta
result = (num1 - num2);
DisplayResult.Text = result.ToString();
break;
case '*': //multiply
result = (num1 * num2);
DisplayResult.Text = result.ToString();
break;
case '/': //division
if (num2 != 0)
{
result = (num1 / num2);
DisplayResult.Text = result.ToString();
}
else
{
DisplayResult.Text = "Can't divide by 0";
}
break;
}
}
catch (Exception ex)
{
MessageBox.Show("Unexpected error occured. Details: " +
ex.Message);
}
}
}
private void buttonBackSpace_Click(object sender, EventArgs e)
{
try
{
String Value = DisplayResult.Text.ToString();
int temp = Value.Length;
if (temp == 1)
DisplayResult.Text = String.Empty;
else
{
DisplayResult.Text = DisplayResult.Text.Substring(0, temp - 1);
}
}
catch (Exception ex)
{
MessageBox.Show("Unexpected error in buttonBackSpace occured. Details: " +
ex.Message);
}
}
private void buttonClear_Click(object sender, EventArgs e)
{
DisplayResult.Text = String.Empty;
}
private void buttonDecimal_Click(object sender, EventArgs e)
{
if (DisplayResult.Text.Contains("."))
{
return;
}
DisplayResult.Text += ".";
}
private void DecimalRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (DecimalRadioButton.Checked == true)
{
DisplayResult.Text= BaseToDecimal(DisplayResult.Text.ToString(), 2).ToString();
}
buttonTow.Enabled = true;
buttonThree.Enabled = true;
buttonFour.Enabled = true;
buttonFive.Enabled = true;
buttonSix.Enabled = true;
buttonSeven.Enabled = true;
buttonEight.Enabled = true;
buttonNine.Enabled = true;
}
private void BinaryRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (BinaryRadioButton.Checked == true)
{
DisplayResult.Text = DecimalToBase(Convert.ToInt16(DisplayResult.Text.ToString()), 2);
buttonTow.Enabled = false;
buttonThree.Enabled = false;
buttonFour.Enabled = false;
buttonFive.Enabled = false;
buttonSix.Enabled = false;
buttonSeven.Enabled = false;
buttonEight.Enabled = false;
buttonNine.Enabled = false;
}
}
string DecimalToBase(int iDec, int numbase)
{
string strBin = "";
int[] result = new int[32];
int MaxBit = 32;
for (; iDec > 0; iDec /= numbase)
{
int rem = iDec % numbase;
result[--MaxBit] = rem;
}
for (int i = 0; i < result.Length; i++)
if ((int)result.GetValue(i) >= base10)
strBin += cHexa[(int)result.GetValue(i) % base10];
else
strBin += result.GetValue(i);
strBin = strBin.TrimStart(new char[] { '0' });
return strBin;
}
int BaseToDecimal(string sBase, int numbase)
{
int dec = 0;
int b;
int iProduct = 1;
string sHexa = "";
if (numbase > base10)
for (int i = 0; i < cHexa.Length; i++)
sHexa += cHexa.GetValue(i).ToString();
for (int i = sBase.Length - 1; i >= 0; i--, iProduct *= numbase)
{
string sValue = sBase[i].ToString();
if (sValue.IndexOfAny(cHexa) >= 0)
b = iHexaNumeric[sHexa.IndexOf(sBase[i])];
else
b = (int)sBase[i] - asciiDiff;
dec += (b * iProduct);
}
return dec;
}
}
}
When converting a number with a decimal point from decimal to binary, this is what you do: first you take the part before the decimal point and convert it (in the usual way) to binary; and the part after the decimal point you multiply by 2 and see if it is >= 1; if it is not, write 0 and keep multiplying. You are done when it is = 1.00. For example:
2.25 -
You take the 0.25;
0.25 * 2 = 0.50 --> 0,
0.50 * 2 = 1.00 --> 1, and you just read the numbers.
So, 0.25 would be 0.01 (2.25 would be 10.01 binary.)

How to make a TextBox accept only alphabetic characters?

How can I make a TextBox only accept alphabetic characters with spaces?
You could use the following snippet:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]"))
{
MessageBox.Show("This textbox accepts only alphabetical characters");
textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
You can try by handling the KeyPress event for the textbox
void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}
Additionally say allow backspace in case you want to remove some text, this should work perfectly fine for you
EDIT
The above code won't work for paste in the field for which i believe you will have to use TextChanged event but then it would be a bit more complicated with you having to remove the incorrect char or highlight it and place the cursor for the user to make the correction Or maybe you could validate once the user has entered the complete text and tabs off the control.
private void textbox1_KeyDown_1(object sender, KeyEventArgs e)
{
if (e.Key >= Key.A && e.Key <= Key.Z)
{
}
else
{
e.Handled = true;
}
}
The simplest way is to handle the TextChangedEvent and check what's been typed:
string oldText = string.Empty;
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text.All(chr => char.IsLetter(chr)))
{
oldText = textBox2.Text;
textBox2.Text = oldText;
textBox2.BackColor = System.Drawing.Color.White;
textBox2.ForeColor = System.Drawing.Color.Black;
}
else
{
textBox2.Text = oldText;
textBox2.BackColor = System.Drawing.Color.Red;
textBox2.ForeColor = System.Drawing.Color.White;
}
textBox2.SelectionStart = textBox2.Text.Length;
}
This is a regex-free version if you prefer. It will make the text box blink on bad input.
Please note that it also seems to support paste operations as well.
Write Code in Text_KeyPress Event as
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsLetter(e.KeyChar))
{
e.Handled = true;
}
}
This one is working absolutely fine...
private void manufacturerOrSupplierTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsControl(e.KeyChar) || char.IsLetter(e.KeyChar))
{
return;
}
e.Handled = true;
}
This solution uses regular expressions, does not allow invalid characters to be pasted into the text box and maintains the cursor position.
using System.Text.RegularExpressions;
int CursorWas;
string WhatItWas;
private void textBox1_Enter(object sender, EventArgs e)
{
WhatItWas = textBox1.Text;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]*$"))
{
WhatItWas = textBox1.Text;
}
else
{
CursorWas = textBox1.SelectionStart == 0 ? 0 : textBox1.SelectionStart - 1;
textBox1.Text = WhatItWas;
textBox1.SelectionStart = CursorWas;
}
}
Note: textBox1_TextChanged recursive call.
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z]+$"))
{
}
else
{
textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
MessageBox.Show("Enter only Alphabets");
}
Please Try this
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9')
e.Handled = true;
else
e.Handled = false;
}
Try This
private void tbCustomerName_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back||e.KeyChar==(char)Keys.Space);
}
It Allows White Spaces Too
you can try following code that alert at the time of key press event
private void tbOwnerName_KeyPress(object sender, KeyPressEventArgs e)
{
//===================to accept only charactrs & space/backspace=============================================
if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
{
e.Handled = true;
base.OnKeyPress(e);
MessageBox.Show("enter characters only");
}
Here is my solution and it works as planned:
string errmsg = "ERROR : Wrong input";
ErrorLbl.Text = errmsg;
if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
{
ErrorLbl.Text = "ERROR : Wrong input";
}
else ErrorLbl.Text = string.Empty;
if (ErrorLbl.Text == errmsg)
{
Nametxt.Text = string.Empty;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar) &&
(e.KeyChar !='.'))
{
e.Handled = true;
MessageBox.Show("Only Alphabets");
}
}
Try following code in KeyPress event of textbox
if (char.IsLetter(e.KeyChar) == false &
Convert.ToString(e.KeyChar) != Microsoft.VisualBasic.Constants.vbBack)
e.Handled = true
works for me, even though not the simplest one.
private void Alpha_Click(object sender, EventArgs e)
{
int count = 0;
foreach (char letter in inputTXT.Text)
{
if (Char.IsLetter(letter))
{
count++;
}
else
{
count = 0;
}
}
if (count != inputTXT.Text.Length)
{
errorBox.Text = "The input text must contain only alphabetic characters";
}
else
{
errorBox.Text = "";
}
}
This works fine as far as characters restriction, Any suggestions on error msg prompt with my code if it's not C OR L
Private Sub TXTBOX_TextChanged(sender As System.Object, e As System.EventArgs) Handles TXTBOX.TextChanged
Dim allowed As String = "C,L"
For Each C As Char In TXTBOX.Text
If allowed.Contains(C) = False Then
TXTBOX.Text = TXTBOX.Text.Remove(TXTBOX.SelectionStart - 1, 1)
TXTBOX.Select(TXTBOX.Text.Count, 0)
End If
Next
End Sub
Try this one. Spaces and shortcut keys work
if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsSeparator(e.KeyChar))
{
e.Handled = true;
}

Categories