C# Windows form application InvalidCastException problem - c#

This is a simple calculator program I am trying to make using Windows Forms Application in VS. The UnhandledException appears when I click anywhere except on the calculator buttons. I am fairly new to C# and it seems that a sender button in my function "common_operators" is causing the exception. Also, I want this calculator to have similar memory functionalities as windows 10's built-in calculator. I've searched everywhere but couldn't find a c# calculator implementation that is similar to Win10's built-in calculator has, I have already started but I think there's a better way to implement it. If u need more info, I've uploaded the "designer.cs" file that relates to the form application.
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;
using WindowsFormsApp_Calculator;
namespace WindowsFormsApp_Calculator
{
public partial class CalculatorBase : Form
{
public double[] arrMemory = new double[5];
public int indexer = 0;
double result = 0;
string asmd_operator = ""; // ASMD - Addition, Subtraction, Multiplication, Division
bool insert_value = false;
public CalculatorBase()
{
InitializeComponent();
btn_mc.Enabled = false;
btn_mr.Enabled = false;
mem_textbox.Text = "There's nothing saved in memory";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void numbers_zerotonine(object sender, EventArgs e)
{
Button b = (Button)sender;
if((box_display.Text == "0") || insert_value)
box_display.Text = "";
insert_value = false;
box_display.Text = box_display.Text + b.Text;
}
private void common_operators(object sender, EventArgs e)
{
Button b = (Button)sender;
if (result != 0)
{
btn_eql.PerformClick();
insert_value = true;
asmd_operator = b.Text;
subbox_display.Text = result + " " + asmd_operator;
}
else
{
asmd_operator = b.Text;
result = double.Parse(box_display.Text);
box_display.Text = "";
subbox_display.Text = System.Convert.ToString(result) + " " + asmd_operator;
}
}
private void btn_ce_Click(object sender, EventArgs e)
{
box_display.Text = "0";
}
private void btn_c_Click(object sender, EventArgs e)
{
box_display.Text = "0";
subbox_display.Text = "";
result = 0;
}
private void btn_eql_Click(object sender, EventArgs e)
{
subbox_display.Text = "";
switch(asmd_operator)
{
case "-":
box_display.Text = (result - double.Parse(box_display.Text)).ToString();
break;
case "+":
box_display.Text = (result + double.Parse(box_display.Text)).ToString();
break;
case "X":
box_display.Text = (result * double.Parse(box_display.Text)).ToString();
break;
case "/":
box_display.Text = (result / double.Parse(box_display.Text)).ToString();
break;
default:
break;
}
result = double.Parse(box_display.Text);
asmd_operator = "";
}
private void btn_bs_Click(object sender, EventArgs e)
{
if(box_display.Text.Length > 0)
{
box_display.Text = box_display.Text.Remove(box_display.Text.Length - 1, 1);
}
if(box_display.Text == "")
{
box_display.Text = "0";
}
}
private void btn_ms_Click(object sender, EventArgs e)
{
if (indexer == 5)
{
mem_textbox.Text = "Memory is full. Max limit = 5";
}
else
{
int hgt = 75;
mem_textbox.Text = "";
arrMemory[indexer] = double.Parse(box_display.Text);
indexer++;
btn_mc.Enabled = true;
btn_mr.Enabled = true;
TextBox mem = new TextBox();
mem.Multiline = true;
mem.TextAlign = HorizontalAlignment.Right;
mem.Width = 275;
mem.Height = 70;
mem.Font = new Font(mem.Font.FontFamily, 20);
mem.Text = box_display.Text;
mem.Location = new Point(387, hgt);
this.Controls.Add(mem);
}
}
private void btn_mc_Click(object sender, EventArgs e)
{
foreach (int i in arrMemory)
{
arrMemory[i] = 0;
}
indexer = 0;
btn_mr.Enabled = false;
btn_mc.Enabled = false;
mem_textbox.Text = "There's nothing saved in memory";
}
private void btn_mr_Click(object sender, EventArgs e)
{
box_display.Text = arrMemory[indexer].ToString();
}
private void btn_mp_Click(object sender, EventArgs e)
{
arrMemory[indexer] += double.Parse(box_display.Text);
}
private void btn_mm_Click(object sender, EventArgs e)
{
arrMemory[indexer] -= double.Parse(box_display.Text);
}
}
}

From your designer.cs you've got a Click event handler on the form itself that invokes common_operators, so if that gets fired, it will be an invalid cast since sender will be your CalculatorBase form type and not Button

Related

facing problem in c# calculator operator pressed it shows calculates result while pressing another operator

I am new to c# programming.I am building a simple calculator but when i add two numbers and press operator(+) button it adds two numbers but when i again press another operator it just adds the previous value like 2+2= 4 and if i press (-) operator after that it just shows result = 8 , please help me to get out of this.
thanks.
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 Calculator
{
public partial class Form1 : Form
{
double value = 0;
string operation = "";
bool opt_pressed = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if ((txtMain.Text == "0") || (opt_pressed))
txtMain.Clear();
Button a = (Button)sender;
opt_pressed = false;
if (a.Text == ".")
{
if (!txtMain.Text.Contains("."))
txtMain.Text = txtMain.Text + a.Text;
}
else
{
txtMain.Text = txtMain.Text + a.Text;
}
}
private void txtMain_TextChanged(object sender, EventArgs e)
{
}
private void button10_Click(object sender, EventArgs e)
{
txtMain.Clear();
value = 0;
label1.Text = "";
}
private void button11_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if (value != 0)
{
equal.PerformClick();
operation = b.Text;
label1.Text = value + " " + operation;
opt_pressed = true;
}
else
{ operation = b.Text;
value = double.Parse(txtMain.Text);
label1.Text = value + " " + operation;
opt_pressed = true;
}
}
private void button16_Click(object sender, EventArgs e)
{
switch (operation)
{
case "+":
txtMain.Text = (value + double.Parse(txtMain.Text)).ToString();
break;
case "-":
txtMain.Text = (value - double.Parse(txtMain.Text)).ToString();
break;
case "/":
txtMain.Text = (value / double.Parse(txtMain.Text)).ToString();
break;
case "*":
txtMain.Text = (value * double.Parse(txtMain.Text)).ToString();
break;
}
value = double.Parse(txtMain.Text);
label1.Text = "";
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, KeyPressEventArgs e)
{
Button a = (Button)sender;
button1.PerformClick();
operation = a.Text;
}
}
}

PictureBox in Windows Forms - How to open an image by clicking on it to see it in full resolution

How created a simple slideshow with a PictureBox element.
Now I would like to open an image by clicking on it to see it in full resolution - with the default app which is associated with .jpg files (e.g. Microsoft Photos). I think a click event on the PictureBox would be the way to go but I don't know what code to add. Couldn't find a good example on the internet.
Following the code I use so far:
using System;
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 Diashow
{
public partial class Form1 : Form
{
private string[] folderFile = null;
private int selected = 0;
private int begin = 0;
private int end = 0;
public Form1()
{
InitializeComponent();
this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
folderBrowserDialog1.SelectedPath = #"E:\MiscTest\";
timer1.Interval = 5000;
}
private void btnOpen_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
string[] part1 = null, part2 = null, part3 = null;
part1 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpg");
part2 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpeg");
part3 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.tif");
folderFile = new string[part1.Length + part2.Length + part3.Length];
Array.Copy(part1, 0, folderFile, 0, part1.Length);
Array.Copy(part2, 0, folderFile, part1.Length, part2.Length);
Array.Copy(part3, 0, folderFile, part1.Length + part2.Length, part3.Length);
selected = 0;
begin = 0;
end = folderFile.Length;
showImage(folderFile[selected]);
btnPrevious.Enabled = true;
btnNext.Enabled = true;
bntSlideshow.Enabled = true;
}
}
private void showImage(string path)
{
Image imgtemp = Image.FromFile(path);
pictureBox1.Image = imgtemp;
}
private void btnNext_Click(object sender, EventArgs e)
{
if (selected == folderFile.Length - 1)
{
selected = 0;
showImage(folderFile[selected]);
}
else
{
selected = selected + 1; showImage(folderFile[selected]);
}
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (selected == 0)
{
selected = folderFile.Length - 1;
showImage(folderFile[selected]);
}
else
{
selected = selected - 1; showImage(folderFile[selected]);
}
}
private void nextImage()
{
if (selected == folderFile.Length - 1)
{
selected = 0;
showImage(folderFile[selected]);
}
else
{
selected = selected + 1; showImage(folderFile[selected]);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
pictureBox1.Image.Dispose();
}
nextImage();
}
private void bntSlideshow_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
timer1.Enabled = false;
bntSlideshow.Text = "START Slideshow";
}
else
{
timer1.Enabled = true;
bntSlideshow.Text = "STOP Slideshow";
}
}
}
}

c# Flappybird "Non-invocable member cannot be used like a method"

I'm trying to re-create flappybird in Visual studio 2015 c# for a little school project. But for some reason i get this error that i really can't fix. I'm following an tutorial on how to create flappybird, but the one making the tutorial is writing in VB.net Heres the YT Link and under that my code I'm trying to make.
https://www.youtube.com/watch?v=tnjdMbdEzMo
public partial class Form10 : Form
{
int gravity = 1;
int yspeed = 0;
PictureBox[,] Pipe;
public Form10()
{
InitializeComponent();
}
private void gameTimer_Tick(object sender, EventArgs e)
{
int i;
this.yspeed += this.gravity;
bird.Top += this.yspeed;
}
private void inGameKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
this.yspeed = -15;
}
}
private void pausePlayToolStripMenuItem_Click(object sender, EventArgs e)
{
if (gameTimer.Enabled == true)
{
gameTimer.Enabled = false;
}
else
{
if (gameTimer.Enabled == false)
{
gameTimer.Enabled = true;
}
}
}
private void restartToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void startGame_Click(object sender, EventArgs e)
{
if (gameTimer.Enabled == false)
{
gameTimer.Enabled = true;
startGame.Enabled = false;
}
}
private void CreatePipes(int number)
{
int i = 0;
for (i = 0; (i <= number); i++)
{
var temp = new PictureBox();
this.Controls.Add(temp);
temp.Width = 50;
temp.Height = 370;
temp.BorderStyle = BorderStyle.FixedSingle;
temp.BackColor = Color.Red;
temp.Top = 50;
temp.Left = (2 * 200) + 300;
Pipe(i) = temp;
Pipe(i).Visable = true;
}
}
private void Form10_Load(object sender, EventArgs e)
{
gameTimer.Enabled = true;
CreatePipes(1);
}
}
}
The problem you are seeing is in the lines
Pipe(i) = temp;
Pipe(i).Visable = true;
If you are trying to access Pipe as an array, the syntax is Pipe[i], although pipe is a 2d array so it should be Pipe[i,j] Where j is something else.
Also you have misspelled Visible.

Windows.Forms.Timer not working properly

I am posting a sample code to decode a problem with a larger code.
I have a 2 seconds timer - System.Windows.Forms.Timer
Every 2 seconds i increment a global int by one, and show its value using MessageBox
If the int reaches 4, i turn off the main flag.
Here is the code
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
bool Play_On = false;
int i = 0;
public Form1()
{
InitializeComponent();
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Play")
{
button1.Text = "Puase";
Play_On = true;
}
else
{
button1.Text = "Play";
Play_On = false;
}
}
private void Form1_Load(object sender, EventArgs e)
{
Timer MinResTimer = new Timer();
{
MinResTimer.Tick += new EventHandler(MinResTimer_Elapsed);
MinResTimer.Interval = 2000;
MinResTimer.Enabled = true;
MinResTimer.Start();
}
}
public void MinResTimer_Elapsed(object sender, EventArgs e)
{
if (Play_On == true)
{
MessageBox.Show("timed"+ i.ToString());
i++;
}
if (i == 4)
{
Play_On = false;
button1.Text = "Play";
}
}
}
}
The problem is that the flag isnt being turned off at all.
The output I am getting is Timed0 - In a messagebox, many times.
I think I have some problem with the messagebox - not sure
Could someone help me find out whats going on here?
Move your increment of i++ to before you call MessageBox
Then you will see that you really want to protect the event from still firing while the message box is displayed.
so your new code would move the I++ to before the MessageBox and then you would disable and enable the timer before and after the message box is called.
When the messagebox show,then you didn't click the 'OK' button to close the messagebox, i++ can not do.So i always equals 0 before you click the 'OK' button on messagebox.
void MinResTimer_Elapsed(object sender, EventArgs e)
{
if (Play_On == true)
{
i++;
MessageBox.Show("timed" + i.ToString());
}
if (i == 4)
{
Play_On = false;
MinResTimer.Enabled = false;
button1.Text = "Pause";
}
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Play")
{
button1.Text = "Puase";
MinResTimer.Enabled = true;
i = 0;
Play_On = true;
}
else
{
button1.Text = "Play";
MinResTimer.Enabled = false;
Play_On = false;
}
}
EDIT #1:
bool Play_On = false;
int i = 0;
Timer MinResTimer;
private void Form1_Load(object sender, EventArgs e)
{
MinResTimer = new Timer();
{
MinResTimer.Tick += new EventHandler(MinResTimer_Elapsed);
MinResTimer.Interval = 2000;
MinResTimer.Enabled = true;
MinResTimer.Start();
}
}
void MinResTimer_Elapsed(object sender, EventArgs e)
{
if (Play_On == true && i <= 4)
{
i++;
MessageBox.Show("timed" + i.ToString());
}
if (i == 4)
{
Play_On = false;
button1.Text = "Pause";
}
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Play")
{
button1.Text = "Puase";
Play_On = true;
}
else
{
button1.Text = "Play";
Play_On = false;
}
}

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

Categories