Stumped on calculator operations in C# - c#

I was making a calculator using Windows Forms Application and I'm currently stumped.
Here's my application so far, it can only do addition, but any amount of numbers.
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 Calculator
{
public partial class Form1 : Form
{
int num;
int answer = 0;
int i;
public Form1()
{
InitializeComponent();
}
private void plusButton_Click(object sender, EventArgs e)
{
answer += System.Convert.ToInt32(textBox1.Text);
ClearTextbox();
}
private void minusButton_Click(object sender, EventArgs e)
{
//answer -= System.Convert.ToInt32(textBox1.Text);
//ClearTextbox();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void divideButton_Click(object sender, EventArgs e)
{
}
private void multiplyButton_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
num = 1;
displayInt(num);
}
private void button2_Click(object sender, EventArgs e)
{
num = 2;
displayInt(num);
}
private void button3_Click(object sender, EventArgs e)
{
num = 3;
displayInt(num);
}
private void button4_Click(object sender, EventArgs e)
{
num = 4;
displayInt(num);
}
private void button5_Click(object sender, EventArgs e)
{
num = 5;
displayInt(num);
}
private void button6_Click(object sender, EventArgs e)
{
num = 6;
displayInt(num);
}
private void button7_Click(object sender, EventArgs e)
{
num = 7;
displayInt(num);
}
private void button8_Click(object sender, EventArgs e)
{
num = 8;
displayInt(num);
}
private void button9_Click(object sender, EventArgs e)
{
num = 9;
displayInt(num);
}
private void button0_Click(object sender, EventArgs e)
{
num = 0;
displayInt(num);
}
private void resetButton_Click(object sender, EventArgs e)
{
ClearTextbox();
num = 0;
answer = 0;
}
public void displayInt(int num)
{
textBox1.Text = textBox1.Text + num.ToString();
}
public void ClearTextbox()
{
textBox1.Clear();
}
public void DisplayAnswer(int answer)
{
answer += System.Convert.ToInt32(textBox1.Text); //Answer = Answer + Textbox Stuff
textBox1.Clear();
textBox1.Text = answer.ToString();
}
private void equalsButton_Click(object sender, EventArgs e)
{
DisplayAnswer(answer);
num = 0;
answer = 0;
}
}
}
I'm not sure if there's a way to wait until another number key is pressed, and then do x + y. I heard about event handlers, but it's quite a vague topic to me.
Here's a picture: http://img196.imageshack.us/img196/4127/12464e13e5154a949a9a457.png
*I want it to be able to do operations to more then 2 numbers.
Thanks!

Your code is a bit messy and it's hard to figure out your intent. Help with this code will be long in coming. I suggest following this simple calculator tutorial. It explains the concepts and steps very nicely, including button events.

You would need to have a "+"-button and a "="-button. Then your calculator has two number fields and two states:
1) Entering first number
2) Entering second number
You could have a variable saying which number is being entered.
int field = 1;
When pressing a digit button, this digit has to be appended to the corresponding field.
When pressing the "+"-button change the state to
field = 2;
Now the digits will be appended to the second field.
When you press the "="-button, convert the two numbers, which are still strings now, to int's, add them and output them to a result field. Set the state back to
field = 1;
Also a "clear"-button would clear the fields and set field = 1;
Note: As Paul Sasik says, your code is a bit messy. I would help, if you gave your buttons meaningful names like btnDigit1, btnDigit2, btnPlus, btnEquals, btnClear. When you double-click a button in the designer an event handler like btnPlus_Click will be created. This is clearer than button17_Click.

Related

Call method inside a Form

Hi I am learning C# and struggling with a Form in which a btnCalc_click event should call a method calcArea and produce the output in a textBox1.text
the error is in row: textBox1.Text = calcArea.ToString();
who can help with with the correct syntax ?
namespace Meetkunde
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void txbLengte_TextChanged(object sender, EventArgs e)
{
double length = 0;
length = double.Parse(txbLength.Text);
}
private void txbBreedte_TextChanged(object sender, EventArgs e)
{
double width = 0;
width = double.Parse(txbWidth.Text);
}
public double calcArea(double length, double width)
{
double area = 0;
area = (length * width);
return area;
}
private void label3_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void btnCalc_Click(object sender, EventArgs e)
{
textBox1.Text = calcArea.ToString();
}
}
}
As I mentioned above - you need to pass the method the parameters as you defined them in the method. You don't need Text Changed events for this either - plus they aren't doing anything.
Try changing your code to something like (not real sure of what exactly you named textboxes):
private void btnCalc_Click(object sender, EventArgs e)
{
double width = Convert.ToDouble(txbBreedte.Text);//txbWidth.Text?
double length= Convert.ToDouble(txbLengte.Text);//txbLength.Text?
textBox1.Text = calcArea(length, width).ToString();
}
calcArea.ToString();
when you are calling this, you aren't calling the function, you are referencing the function, not the return
do
calcArea(parameters).ToString();
replace parameters with what you want to calculate.

C# can't use variable from IF statement

I'm making easy password generator, but i cant pick int from try and string from if. Here's the code. I hope you help me. I cant make this I as textbox and i cant do nothing with it.
private void button3_Click(object sender, EventArgs e)
{
try
{
int i = Int32.Parse(textBox2.Text);
return;
}
catch
{
}
CreatePassword(i);
}
and here is part of CreatePassword function
public string CreatePassword(int length)
{
if (checkBox2.Checked)
{
const string src = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
return src;
}
else
{
const string src = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
return src;
}
}
There are several problems with your code. First, you're trying to access the variable i outside of the scope in which it is declared; it's not visible outside of the try statement. Second, it seems like you're expecting the password to be generated from the integer you parsed, but you're explicitly returning before the password can be created. Thirdly, you're not doing anything with the created password, just throwing it away.
Try the following:
private void button3_Click(object sender, EventArgs e)
{
try
{
int i = Int32.Parse(textBox2.Text);
string password = CreatePassword(i);
// TODO: use the 'password' string for something.
return;
}
catch
{
}
}
You should also consider using int.TryParse instead, which won't throw an exception.
if (int.TryParse(textbox2.Text, out int i) {
string password = CreatePassword(i);
// Do something with 'password'
} else {
// Display an error.
}
From your example, it looks like all your need is Int32.TryParse:
int.TryParse(textBox2.Text, out int i);
CreatePassword(i);
However, to answer your original question: you need to initialize i variable outside of the try block in order to be able to use it after it. For instance:
int i = 0;
try
{
i = int.Parse("test");
}
catch
{
}
Console.WriteLine(i); // 0
You logic is a bit flawed. If Textbox2 does not contain a valid integer, you ignore the exception and just create a password. What kind of password you expect to create?
I think you mean to do something like this:
private void button3_Click(object sender, EventArgs e)
{
try
{
int i = Int32.Parse(textBox2.Text);
CreatePassword(i);
}
catch
{
// Show a messagebox or something
}
}
Guys all thanks for help. I did it. Here you have my source of my application as thanks for you all. My app completely work and i believe you understand my logic :D
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Password_generator
{
public partial class Form1 : Form
{
private bool _dragging = false;
private Point _start_point = new Point(0, 0);
public Form1()
{
InitializeComponent();
}
public string CreatePassword(int length)
{
string src;
var sb = new StringBuilder();
Random RNG = new Random();
src = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (checkBox2.Checked)
{
src += "1234567890";
}
if (checkBox3.Checked)
{
src += "##$%^&*()";
}
for (var i = 0; i < length; i++)
{
var c = src[RNG.Next(0, src.Length)];
sb.Append(c);
}
textBox1.Text = sb.ToString();
if (checkBox1.Checked)
{
try
{
File.AppendAllText("hesla.txt", textBox1.Text + Environment.NewLine);
}
catch(Exception o)
{
MessageBox.Show("Něco se nepovedlo! " + Environment.NewLine + "(" + o.Message + ")");
}
}
return textBox1.Text;
}
private void button3_Click(object sender, EventArgs e)
{
try
{
int i = Int32.Parse(textBox2.Text);
CreatePassword(i);
}
catch
{
MessageBox.Show("Musíš zadat číslo!");
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
_dragging = false;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (_dragging)
{
Point p = PointToScreen(e.Location);
Location = new Point(p.X - this._start_point.X, p.Y - this._start_point.Y);
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
_dragging = true;
_start_point = new Point(e.X, e.Y);
}
private void panel3_Paint(object sender, PaintEventArgs e)
{
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
try
{
Clipboard.SetText(textBox1.Text);
}
catch
{
}
}
}
}

Customization censored in textBox

I have problem, which consists in aesthetic sense, correctly - There is textBox to which i apply true condition of UseSystemPasswordChar.. It's work! But i get bold points. Try to change font size - decreases textbox's field. Below is the code (although why is it here?). Can anyone help, thank you in advance)
public partial class frmRegistr : Form
{
public frmRegistr()
{
InitializeComponent();
}
int counter = 0;
int a = 0;
string b;
private void frmRegistr_Load(object sender, EventArgs e)
{
b = label1.Text;
a = b.Length;
label1.Text = "";
timer1.Start();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
if (counter < a)
{
counter++;
label1.Text = b.Substring(0, counter);
}
else
{
timer1.Stop();
}
}
private void label4_Click(object sender, EventArgs e)
{
timer3.Start();
}
private void label4_MouseHover(object sender, EventArgs e)
{
//if this.MouseLeave
label4.BackColor = Color.FromArgb(((int)(((byte)(154)))), ((int)(((byte)(181)))), ((int)(((byte)(101)))));
}
private void timer2_Tick(object sender, EventArgs e)
{
if (Opacity == 1)
{
timer2.Stop();
}
Opacity += .2;
}
private void timer3_Tick(object sender, EventArgs e)
{
if (Opacity <= 0)
{
this.Close();
}
Opacity -= .2;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox2.UseSystemPasswordChar = true;
}
}
}
If you want to define your own password character, use property TextBox.PasswordChar. If you want this in a certain font, use Control.Font
As you only have to do this once, do this in the constructor:
public MyForm : Form
{
InitializeComponents(),
this.textBox1.PasswordChar = '_';
this.textBox11.Font = new Font(...)
};
You can also decide to do this using the visual studio designer.
You can setup this in VisualStudio designer, but this is code:
textBox1.PasswordChar = '*';
//* = password character

Set an 'int' in one event and use it in another event

I'm making a little something in Windows Form (C# Visual Studio)
But I need to know how I can set an int and then to use it in another event. For example, :
private void BtnYes_Click(object sender, EventArgs e)
{
int yes = 1;
int no = 0;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (yes == 1) {
//EVENT
}
}
When I do this I get some errors. Can anyone help me with this? Or just tell me how to do something like this using a different technique?
U need to use a field for this:
private int _yes;
private void BtnYes_Click(object sender, EventArgs e)
{
_yes = 1;
int no = 0;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (_yes == 1) {
//EVENT
}
}
The variable "yes" you are declaring is only visible in the scope of the method. By making it a field of class, this would make it visible to all methods in the class (when private).
class YourClass
{
private int yes = 1;
private int no = 0;
private void BtnYes_Click(object sender, EventArgs e)
{
//Remove the type declaration here to use the class field instead. If you leave the type declaration, the variable here will be used instead of the class field.
yes = 1;
no = 0;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (yes == 1) {
//EVENT
}
}
}

How can I add (append) a word to the same sentence, using one button (click) per word

I greatly appreciate any help. I have 20+ buttons, each with a word, or a space or period. Each time I click on a button, the pre-existing word is wiped out and replaced with the new word. I need each word and/or space to remain in place until I click the "Clear" button.
Maybe this has been previously asked/answered under different search terms? I tend to believe I need to identify a string variable, but have no idea how to begin.
==============
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 WindowsFormsApplication1
{
public partial class frmSentenceBuilder : Form
{
public frmSentenceBuilder()
{
InitializeComponent();
}
private void frmSentenceBuilder_Load(object sender, EventArgs e)
{
}
private void btnA_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnA.Text;
}
private void btn_a_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btn_a.Text;
}
private void btnAn_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnAn.Text;
}
private void btn_an_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btn_an.Text;
}
private void btnThe_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnThe.Text;
}
private void btn_the_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btn_the.Text;
}
private void btnman_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnman.Text;
}
private void btnwoman_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnwoman.Text;
}
private void btndog_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btndog.Text;
}
private void btncat_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btncat.Text;
}
private void btncar_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btncar.Text;
}
private void btnbicycle_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnbicycle.Text;
}
private void btnbeautiful_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnbeautiful.Text;
}
private void btnbig_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnbig.Text;
}
private void btnsmall_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnsmall.Text;
}
private void btnstrange_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnstrange.Text;
}
private void btnlookedat_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnlookedat.Text;
}
private void btnrode_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnrode.Text;
}
private void btnspoketo_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnspoketo.Text;
}
private void btnlaughedat_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnlaughedat.Text;
}
private void btndrove_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btndrove.Text;
}
private void btnSpace_Click(object sender, EventArgs e)
{
lblSentenceText.Text = " ";
}
private void btnperiod_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnperiod.Text;
}
private void btnexclam_Click(object sender, EventArgs e)
{
lblSentenceText.Text = btnexclam.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
lblSentenceText.Text = "";
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Use lb1SentenceText.Text+=whatever.Text;.
+= is equivalent to lbSentence.Text = lblSentenceText.Text + whatever.Text.
Basically, it appends or concatenates the right hand side string to the string on the left hand side. Hope it makes sense?
So:
string rhs="Hello " ;
string lhs = "World";
string rhs = rhs + lhs;//Hello World
Please be inspired. You have a lot of redundant code.
btnA.Click += AppendButtonText;
btn_a.Click += AppendButtonText;
...
private void AppendButtonText(object sender, EventArgs e)
{
var button = sender as Button;
if (button != null)
{
lblSentenceText.Text += button.Text;
}
}
On the button click events, change it to += instead of = (except in the clear button). This is equivalent to writing something = something + newValue;.
Try:
lb1SentenceText.Text = lb1SentenceText.Text + *something*.text
The += operator means add to, and the variable modified is equal to the added (Int, String) appended to the original value (x = 1; x += 3; x is now 4)
Try this:
button.Click += new System.EventHandler(ButtonClick);
button1.Click += new System.EventHandler(ButtonClick);
// And for each button, one of those.
private void ButtonClick(object sender, System.EventArgs e)
{
// Do whatever you want to do here, you can place the TEXT to be appended on the button, if so:
lb1SentenceText.Text += sender.Text;
}
//Simple.Create a global variable and within each button click event do this;
string yourStrVar = ""; //Must be global
yourStrVar+= ((Button)sender).Text

Categories