I am in in study phase of asp.net so decided to do an online calculator. The issue is when i do a calculation 1 + 5 = it does not give any output at all. I tried a debugging.
Click button 1 :
first value = 1;
click button + :
first value = null;
click button 5 :
first value = 5
click button =
NOTHING :)
Here is my c# code :
public partial class _Default : System.Web.UI.Page
{
string firstOperand;
string secondOperand;
string Operator;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnOff_Click(object sender, EventArgs e)
{
txtScreen.Enabled = false;
ClearVariables();
}
protected void btnOn_Click(object sender, EventArgs e)
{
txtScreen.Enabled = true;
ClearVariables();
}
private void ClearVariables()
{
firstOperand = "";
secondOperand = "";
Operator = "";
}
protected void Operand(string value)
{
if (value == null) return;
try
{
txtScreen.Text = value;
if (firstOperand == null)
{
firstOperand = value;
}
else
{
if (Operator == null)
{
firstOperand.Insert(firstOperand.Length, value);
}
else
{
secondOperand.Insert(secondOperand.Length, value);
}
}
}
catch (Exception ex)
{
}
}
protected void Num1_Click(object sender, EventArgs e)
{
txtScreen.Text = Num1.Text;
Operand(Num1.Text);
}
protected void Num2_Click(object sender, EventArgs e)
{
txtScreen.Text = Num2.Text;
Operand(Num2.Text);
}
protected void Num3_Click(object sender, EventArgs e)
{
txtScreen.Text = Num3.Text;
Operand(Num3.Text);
}
protected void Num4_Click(object sender, EventArgs e)
{
txtScreen.Text = Num4.Text;
Operand(Num4.Text);
}
protected void Num5_Click(object sender, EventArgs e)
{
txtScreen.Text = Num5.Text;
Operand(Num5.Text);
}
protected void Num6_Click(object sender, EventArgs e)
{
txtScreen.Text = Num6.Text;
Operand(Num6.Text);
}
protected void Num7_Click(object sender, EventArgs e)
{
txtScreen.Text = Num7.Text;
Operand(Num7.Text);
}
protected void Num8_Click(object sender, EventArgs e)
{
txtScreen.Text = Num8.Text;
Operand(Num8.Text);
}
protected void Num9_Click(object sender, EventArgs e)
{
txtScreen.Text = Num9.Text;
Operand(Num9.Text);
}
protected void Num0_Click(object sender, EventArgs e)
{
txtScreen.Text = Num0.Text;
Operand(Num0.Text);
}
protected void btnClr_Click(object sender, EventArgs e)
{
txtScreen.Text = "";
ClearVariables();
}
protected void OpDiv_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
txtScreen.Text = "";
Operator = OpDiv.Text;
}
}
protected void OpMul_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
txtScreen.Text = "";
Operator = OpMul.Text;
}
}
protected void OpSub_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
txtScreen.Text = "";
Operator = OpSub.Text;
}
}
protected void OpAdd_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
txtScreen.Text = "";
Operator = OpAdd.Text;
}
}
protected void OpEqual_Click(object sender, EventArgs e)
{
if (firstOperand == null && Operator == null)
{
return;
}
else if (firstOperand != null && Operator != null && secondOperand == null)
{
secondOperand = firstOperand;
}
else
{
double num1;
double num2;
try
{
num1 = Double.Parse(firstOperand);
num2 =Double.Parse(secondOperand);
{
switch (Operator)
{
case "+":
num1 += num2;
firstOperand = num1.ToString();
txtScreen.Text = firstOperand;
break;
case "-":
num1 -= num2;
firstOperand = num1.ToString();
txtScreen.Text = firstOperand;
break;
case "/":
if (num2 == 0)
{
txtScreen.Text = "Divison by zero";
}
else
{
num1 /= num2;
firstOperand = num1.ToString();
txtScreen.Text = firstOperand;
}
break;
case "*":
num1 *= num2;
firstOperand = num1.ToString();
txtScreen.Text = firstOperand;
break;
default: txtScreen.Text = "Invalid Operation";
break;
}
}
}
catch (Exception ex)
{
txtScreen.Text = "Not a valid Number";
ClearVariables();
}
}
ClearVariables();
}
protected void OpDot_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
if (Operator == null)
{
firstOperand.Insert(firstOperand.Length, ".");
}
else
{
secondOperand.Insert(secondOperand.Length, ".");
}
}
}
}
Could someone explain what is happening? And how to resolve the same.
Thanks
OK. Its simple here, your values are refreshing on postback. so simply hold the values in viewstate.
And before that do reduce your code lines.
you have
protected void Num5_Click(object sender, EventArgs e)
{
txtScreen.Text = Num5.Text;
Operand(Num5.Text);
}
arround 10 events like this. so do first make it a single event like
protected void Num_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
txtScreen.Text = btn.Text;
Operand(btn.Text);
}
and assign this event as Click event for every numeric button
Now in Operand Method make something like
private void Operand(string value)
{
if(ViewState["FirstOperand"] == null)
ViewState["FirstOperand"] = value;
else if(ViewState["SecondOperand"] == null)
ViewState["SecondOperand"] = value;
}
similarly reduce you code for add, sub, mul, divide operator click events as i just showed above for numeric button click events.
and also set the operator value in ViewState["Operator"].
and finally in your OpEqual_Click event. initally set first and second operand like
if(ViewState["FirstOperand"] != null)
firstOperand = ViewState["FirstOperand"].ToString();
if(ViewState["SecondOperand"] != null)
secondOperand = ViewState["SecondOperand"].ToString();
if(ViewState["Operator"] != null)
Operator = ViewState["Operator"].ToString();
Hope this helps
It appears to me that your problem is in your ASP.Net environment and/or your IDE, rather than in your code. I do not know ASP.Net well, but it I do know C# and I notice these two odd facts:
Your debugging shows firstOperand being reset to null or the current operand after every event.
But, you code never sets firstOperand to null. It does set it to the empty string("") in clearVariables, but that is not the same as null ("" != null).
Therefore, I must conclude that something other than your code is setting firstOperand to null. The most logical source of that would be your execution/debugging environment which does reset all object and string variables to null when it initializes for execution, or when it invokes a new Page, Class, Method, etc. (for any variable scoped to those).
Of course you don't want it to do that for every button click, so I have to assume that there is something set wrong in your environment/setup that is causing this.
Hopefully, someone who knows ASP.Net better then I do can explain the rest ...
Yes At last I found it.
It is the problem with sessions. Every time I click button, a new session invokes and all the value resets. So We need to add values in session and recover it.
Like :
Session["Calc"] = firstOperand + ",";
Session["Calc"] += secondOperand + ",";
Session["Calc"] += Operator + ",";
and at page load:
try
{
var Data = Session["Calc"].ToString().Split(',');
if(Data[0] != "")
firstOperand = Data[0];
if (Data[1] != "")
Operator = Data[1];
if (Data[2] != "")
secondOperand = Data[2];
}
catch(Exception ex)
{
}
It is not a good solution I think(still studying asp :) ). And I can use if condition since number of item is fixed to 3.
Related
after clicking my value and pressing my OK_button I cant get the Value out of the listView to save it somewhere else. I cant use listView1.FindItemWithText because I don't have a text to search for.. Idk how to look for the clicked value after I pressed the OK_button
//Create dummy data to display
myData = new string[dataListSize];
for (int i = 0; i < dataListSize; i++)
{
myData[i] = String.Format("{0}", i);
}
}
private void listView1_SearchForVirtualItem(object sender, SearchForVirtualItemEventArgs e)
{
e.Index = Array.FindIndex(myData, s => s == textBox1.Text.ToString());
}
private void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
e.Item = new ListViewItem(myData[e.ItemIndex]);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
String MyString = textBox1.Text.ToString();
ListViewItem lvi = listView1.FindItemWithText(MyString.TrimEnd());
//Select the item found and scroll it into view.
if (lvi != null)
{
listView1.SelectedIndices.Clear();
listView1.SelectedIndices.Add(lvi.Index);
listView1.EnsureVisible(lvi.Index);
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e){ }
private void OK_button_Click(object sender, EventArgs e)
{
try
{
// OK -> Daten übernehmen
int iCount = this.listView1.SelectedIndices.Count;
if (iCount != 1)
{
MessageBox.Show("Value is empty");
return;
}
DialogResult = DialogResult.OK;
Close();
}
catch (Exception)
{
//WriteProtokoll(ex.ToString(), 0);
Close();
}
}
I found out that I can get my value with:
string txt = listView1.FocusedItem.Text;
First of all I'm sorry for the bad title. I'm a beginner so I don't have the vocabulary to accurately express what I need help with within one sentence.
I am currently trying to program a calculator. The calculator looks like this:
All of the buttons in the left area are working perfectly, but I'm having trouble coding for the buttons on the right. The program works by simply taking the string in the display and calculating it, but that doesn't work with the buttons on the right. For example I want the display to show √x and calculate the answer by using Math.Sqrt(x) when the user presses the √-button, I don't want the display to show Math.Sqrt(x).
My code looks like this:
public partial class Calculator : Form
{
String mathOperator;
public Calculator()
{
InitializeComponent();
}
private void number_Click(object sender, EventArgs e)
{
if (tbxDisplay.Text == "0")
{
tbxDisplay.Clear();
}
Button btnNumber = (Button)sender;
tbxDisplay.Text = tbxDisplay.Text + btnNumber.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
tbxDisplay.Text = "0";
}
private void operator_Click(object sender, EventArgs e)
{
Button btnOperator = (Button)sender;
mathOperator = btnOperator.Text;
if ((btnOperator.Text == "(" ) && tbxDisplay.Text == "0")
{
tbxDisplay.Clear();
tbxDisplay.Text = tbxDisplay.Text + btnOperator.Text;
}
else
{
tbxDisplay.Text = tbxDisplay.Text + btnOperator.Text;
}
}
private void btnCalculate_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
var v = dt.Compute(tbxDisplay.Text, "");
string answer = v.ToString();
answer = answer.Replace(',', '.');
if (answer.Contains(".0"))
{
answer = answer.TrimEnd('0');
if (answer.EndsWith("."))
answer = answer.TrimEnd('.');
}
tbxDisplay.Text = answer;
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (tbxDisplay.Text.Length > 0 && tbxSDisplay.Text.Length != 1)
{
tbxDisplay.Text =
tbxDisplay.Text.Remove(tbxDisplay.Text.Length - 1, 1);
}
if (tbxDisplay.Text.Length == 1)
{
tbxDisplay.Text = "0";
}
}
private void btnBack_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.Show();
this.Hide();
}
private void btnPi_Click(object sender, EventArgs e)
{
tbxDisplay.Text = tbxDisplay.Text + "3.14159265359";
//this is my solution for now
//but as you can see it's very ugly
}
}
I'm trying to use autocomplete. The input text comes from a custom made keyboard, made from a form.
I tried autocomplete feature from a simple textbox and text input from my keyboard and works fine. But when I input text from the custom keyboard, it doesn't work. The custom keyboard adds the input from a key listener Key_Click.
I tried adding an extra 'a' and adding the text as txtInput.Text += 'o'; but it didn't work.
Any ideas?
keyboard code:
public partial class frmTextInput : Form
{
public string input_Text { get; set; }
public frmTextInput(string TEXT,bool CTRL)
{
InitializeComponent();
AlternarTeclas(chkShift.Checked);
AgregarListenerTeclas();
var source = new AutoCompleteStringCollection();
List<string> box = Data.Data.SourcePatente();
foreach (var item in box)
{
source.Add(item);
}
txtInput.AutoCompleteCustomSource = source;
txtInput.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtInput.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
private void btnSpace_Click(object sender, EventArgs e)
{
txtInput.Text = txtInput.Text + " ";
}
private void btnBorrar_Click(object sender, EventArgs e)
{
string str = txtInput.Text;
if (!string.IsNullOrEmpty(str))
{
txtInput.Text = str.TrimEnd(str[str.Length - 1]);
}
}
private void btnVolver_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnEnter_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
input_Text = txtInput.Text;
}
private void frmTextInput_Load(object sender, EventArgs e)
{
}
private void chkShift_CheckedChanged(object sender, EventArgs e)
{
AlternarTeclas(chkShift.Checked);
}
private void Key_Click(object sender, EventArgs e)
{
string key = sender.ToString();
if (chkShift.Checked)
{
key = key.ToUpper();
}
else
{
key = key.ToLower();
}
txtInput.Text = txtInput.Text + key.Substring(key.Length - 1);
}
private void AgregarListenerTeclas()
{
foreach (Control c in tabCaracteres.Controls)
{
if (c.GetType() == typeof(Button))
{
if (c.Text.Length == 1 && c.Text != "←")
{
c.Click += Key_Click;
}
}
}
foreach (Control c in tabSymbol.Controls)
{
if (c.GetType() == typeof(Button))
{
if (c.Text.Length == 1 && c.Text != "←")
{
c.Click += Key_Click;
}
}
}
}
private void AlternarTeclas(bool estaShiftApretado)
{
if (estaShiftApretado)
{
foreach (Control c in tabCaracteres.Controls)
{
if (c.GetType() == typeof(Button))
{
if (c.Text.Length < 2)
{
c.Text = c.Text.ToUpper();
}
}
}
}
else
{
foreach (Control c in tabCaracteres.Controls)
{
if (c.GetType() == typeof(Button))
{
if (c.Text.Length < 2)
{
c.Text = c.Text.ToLower();
}
}
}
}
}
private void btnSymbol_Click(object sender, EventArgs e)
{
tabTeclado.SelectTab(tabTeclado.SelectedIndex + 1);
}
private void btnTecAlfanumerico_Click(object sender, EventArgs e)
{
tabTeclado.SelectTab(tabTeclado.SelectedIndex - 1);
}
private void button1_Click(object sender, EventArgs e)
{
txtInput.Text += 'o';
}
}
txtInput.AutoCompleteCustomSource = source;
txtInput.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtInput.AutoCompleteSource = AutoCompleteSource.CustomSource;
This should be put in the designer file of your textbox, not here. Try that, and can you see your textbox text value change when you use the custom keyboard? What I understand is you catch click event for your custom keyboard and change txtInput.Text?
I made it work. First of all, it didn't work with textbox multiline.
Then, the correct way to input new chars was emulate the keyboard:
I was triying in function "Key_Click":
== txtInput.Text = txtInput.Text + key.Substring(key.Length - 1); ==> I don't work
Instead I used:
== txtInput.Focus(); // IMPORTANT
SendKeys.Send(key.Substring(key.Length - 1));
I am new to C#. I need the text of lblBalance to remain as it is when the btnNew is clicked, while it changes according to some calculatios when btnCalc is clicked. Here is my attempt so far.
FIGURED IT OUT, Thanks!
private void btnReset_Click(object sender, EventArgs e)
{
//Reset balance to 0.
balance = 0m;
lblBalance.Text = "";
tbDate.Text = "";
//Call the setupForm procedure.
setupForm();
}
private void setupForm()
{
//Setupform done once to reduce amount of times code must be entered.
//Code to clear these entries and set radio and checkboxes to false.
tbDate.Text = "";
tbAmount.Text = "";
rDeposit.Checked = false;
rWithdrawal.Checked = false;
rFee.Checked = false;
chkBank.Checked = false;
//Return focus to the date textbox
tbDate.Focus();
}
private void btnNew_Click(object sender, EventArgs e)
{
//Clear form, but retain balance when clicked.
setupForm();
}
private void tbDate_TextChanged(object sender, EventArgs e)
{
}
private void lblBalance_Click(object sender, EventArgs e)
{
}
private void btnCalc_Click(object sender, EventArgs e)
{
decimal Amount;
Amount = decimal.Parse(tbAmount.Text);
if ((rDeposit.Checked == true) && (chkBank.Checked == true))
{
Decimal.TryParse(lblBalance.Text, out balance);
lblBalance.Text = Convert.ToString(balance + Amount);
}
else if ((rWithdrawal.Checked == true) && (chkBank.Checked == true))
{
Decimal.TryParse(lblBalance.Text, out balance);
lblBalance.Text = Convert.ToString(balance - Amount);
}
else if ((rFee.Checked == true) && (chkBank.Checked == true))
{
Decimal.TryParse(lblBalance.Text, out balance);
lblBalance.Text = Convert.ToString(balance - Amount);
}
if ((rDeposit.Checked == false) && (rWithdrawal.Checked == false) && (rFee.Checked == false))
{
MessageBox.Show("ERROR: You must select Deposit, Withdrawal, or Service Fee.");
}
}
private void rDeposit_CheckedChanged(object sender, EventArgs e)
{
}
}
}
change:
lblBalance.Text += balance.ToString();
to
lblBalance.Text = balance.ToString();
Inside your btnNew_Click event
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