Post: [C#] Multi Choice Area's
06-13-2011, 03:17 PM #1
(adsbygoogle = window.adsbygoogle || []).push({}); Hey guys, i started learning c++ but i got up to pointers and then started getting into .net and i find C# syntax a lot better.

Anyway just off the top of my head i re-wrote my c++ program to C# (basic console with user I.O)

CODE:
    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Multi_Choice_area_s
{
class Program
{
static void Main(string[] args)
{
//Assigning variables
string shape = "default";
double X, Y, Z;
const double PI = Math.PI;

while (!shape.Equals("exit"))
{
//Showing user the shapes
Console.WriteLine("Options are: Rectangle, Triangle, Circle, Parallelogram, " +
"Trapezium or exit. \"case insensitive\"\n");

Console.Write("\nEnter shape: ");
shape = Console.ReadLine();

switch (shape.ToLower()) //Changes input to lower case for comparing
{
case "rectangle":
Console.Write("Length: ");
X = Convert.ToDouble(Console.ReadLine());

Console.Write("Width/Height: ");
Y = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("\nThe area of the {0} is: {1}", shape, X * Y);
break;

case "triangle":
Console.Write("Height: ");
X = Convert.ToDouble(Console.ReadLine());

Console.Write("Base length: ");
Y = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("The area of the {0} is: {1}", shape, (Y / 2) * X);
break;

case "circle":
Console.Write("Radius: ");
X = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("The area of the {0} is: {1}", shape, PI * (X * X));
break;

case "parallelogram":
goto case "rectangle";

case "trapezium":
Console.Write("Height: ");
X = Convert.ToDouble(Console.ReadLine());

Console.Write("Top Length: ");
Y = Convert.ToDouble(Console.ReadLine());

Console.Write("Base Length: ");
Z = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("The area of the {0} is: {1}", shape, (X / 2) * (Y + Z));
break;

case "exit":
break;

//If anything that is not a shape entered - ERROR
default:
Console.WriteLine("ERROR: unknown shape entered, try again");
break;
}
Console.Write("Press any key to continue/exit");
Console.ReadKey(); //Wait for user
Console.Clear(); //Clear the console
}
}
}
}


I did this fairly quickly (about 20 mins) and I have only been learning C# for a few days, so it will not be the most optimized/decent code, anyway could i have some feedback? Better ways that I could have written this?

(I do have a lot of idea's once I get into form programming, I am capable now but I want to learn most of the syntax and understand .net before I do anything big.)

Thanks,

pro.

[multipage= Calculator for AsianInvasion]
CODE:
    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_for_Asian
{
public partial class Form1 : Form
{
double total1 = 0, total2 = 0;
bool plusButtonClicked = false, minusButtonClicked = false,
multiplyButtonClicked = false, divideButtonClicked = false;

public Form1()
{
InitializeComponent();
}

private void btnOne_Click(object sender, EventArgs e)
{
txtDisplay.Text += btnOne.Text;
}

private void btnTwo_Click(object sender, EventArgs e)
{
txtDisplay.Text += btnTwo.Text;
}

private void btnThree_Click(object sender, EventArgs e)
{
txtDisplay.Text += btnThree.Text;
}

private void btnFour_Click(object sender, EventArgs e)
{
txtDisplay.Text += btnFour.Text;
}

private void btnFive_Click(object sender, EventArgs e)
{
txtDisplay.Text += btnFive.Text;
}

private void btnSix_Click(object sender, EventArgs e)
{
txtDisplay.Text += btnSix.Text;
}

private void btnSeven_Click(object sender, EventArgs e)
{
txtDisplay.Text += btnSeven.Text;
}

private void btnEight_Click(object sender, EventArgs e)
{
txtDisplay.Text += btnEight.Text;
}

private void btnNine_Click(object sender, EventArgs e)
{
txtDisplay.Text += btnNine.Text;
}

private void btnZero_Click(object sender, EventArgs e)
{
txtDisplay.Text += btnZero.Text;
}

private void btnClear_Click(object sender, EventArgs e)
{
txtDisplay.Clear();
}

private void btnPlus_Click(object sender, EventArgs e)
{
total1 += double.Parse(txtDisplay.Text);
txtDisplay.Clear();

plusButtonClicked = true;
minusButtonClicked = false;
multiplyButtonClicked = false;
divideButtonClicked = false;
}

private void btnEquals_Click(object sender, EventArgs e)
{
if (plusButtonClicked == true)
{
total2 = total1 + double.Parse(txtDisplay.Text);
}
else if (minusButtonClicked == true)
{
total2 = total1 - double.Parse(txtDisplay.Text);
}
else if (multiplyButtonClicked == true)
{
total2 = total1 * double.Parse(txtDisplay.Text);
}
else if (divideButtonClicked == true)
{
total2 = total1 / double.Parse(txtDisplay.Text);
}
txtDisplay.Text = total2.ToString();
total1 = 0;
}

private void btnPoint_Click(object sender, EventArgs e)
{
txtDisplay.Text += btnPoint.Text;
}

private void lblCalculator_Click(object sender, EventArgs e)
{

}

private void txtDisplay_TextChanged(object sender, EventArgs e)
{

}

private void btnMinus_Click(object sender, EventArgs e)
{
total1 += double.Parse(txtDisplay.Text);
txtDisplay.Clear();

plusButtonClicked = false;
minusButtonClicked = true;
multiplyButtonClicked = false;
divideButtonClicked = false;
}

private void btnMultiply_Click(object sender, EventArgs e)
{
total1 += double.Parse(txtDisplay.Text);
txtDisplay.Clear();

plusButtonClicked = false;
minusButtonClicked = false;
multiplyButtonClicked = true;
divideButtonClicked = false;
}

private void btnDivide_Click(object sender, EventArgs e)
{
total1 += double.Parse(txtDisplay.Text);
txtDisplay.Clear();

plusButtonClicked = false;
minusButtonClicked = false;
multiplyButtonClicked = false;
divideButtonClicked = true;
}
}
}


Screenshot:
You must login or register to view this content.

[multipage= Basic Text Editor for AsianInvasion]
CODE:
    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 basicwordprocessor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
string Chosen_File = "";
#region properties
openFD.InitialDirectory = "C:";
openFD.Title = "Open a text file";
openFD.FileName = "";
openFD.Filter = "Text Files|*.txt|Word Documents|*.doc";
#endregion

if (openFD.ShowDialog() != DialogResult.Cancel)
{
Chosen_File = openFD.FileName;
txtBox.LoadFile(Chosen_File, RichTextBoxStreamType.PlainText);
}
}

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
string Save_File = "";
#region properties
saveFD.InitialDirectory = "C:";
saveFD.Title = "Save a text file";
saveFD.FileName = "";
saveFD.Filter = "Text File|*.txt";
#endregion

if (saveFD.ShowDialog() != DialogResult.Cancel)
{
Save_File = saveFD.FileName;
txtBox.SaveFile(Save_File, RichTextBoxStreamType.PlainText);
}
}

private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
if (txtBox.Text != "")
{
if (MessageBox.Show("Are you sure you want to quit?", "Warning",
MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)
{
Application.Exit();
}
else
{
Application.Exit();
}
}
}

private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
txtBox.Clear();
}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
if (txtBox.SelectionLength > 0)
{
txtBox.Copy();
}
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{
txtBox.Paste();
}
}
}
}


Screenshot:
You must login or register to view this content.
Last edited by XxprokillahxX ; 06-15-2011 at 09:38 AM.

The following user thanked XxprokillahxX for this useful post:

Epic?
06-14-2011, 03:49 AM #2
Epic?
Awe-Inspiring
Originally posted by XxprokillahxX View Post
Hey guys, i started learning c++ but i got up to pointers and then started getting into .net and i find C# syntax a lot better.

Anyway just off the top of my head i re-wrote my c++ program to C# (basic console with user I.O)

    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Multi_Choice_area_s
{
class Program
{
static int Main(string[] args)
{
//Assigning variables
string shape;
double X, Y, Z, PI = Math.PI;

//Showing user the shapes
Console.WriteLine("Options are: Rectangle, Triangle, Circle, Parallelogram, " +
"Trapezium or exit. (case insensitive)");

for (;Winky Winky
{
Console.WriteLine("Enter shape:");
shape = Console.ReadLine();

switch (shape.ToLower()) //Changes input to lower case for comparing
{
case "rectangle":
Console.WriteLine("Length:");
X = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Width:");
Y = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("The area is: {0}", X * Y);
break;

case "triangle":
Console.WriteLine("Height:");
X = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Base length:");
Y = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("The area is: {0}", (Y / 2) * X);
break;

case "circle":
Console.WriteLine("Radius:");
X = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("The area is: {0}", PI * (X * X));
break;

case "parallelogram":
goto case "rectangle"; //Goto is efficient here for less space

case "trapezium":
Console.WriteLine("Height:");
X = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Top Length:");
Y = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Base Length:");
Z = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("The area is: {0}", (X / 2) * (Y + Z));
break;

case "exit":
return 0; //Couldn't figure any other way to exit/don't know one yet.
}
}
}
}
}


I did this fairly quickly (about 20 mins) and I have only been learning C# for a few days, so it will not be the most optimized/decent code, anyway could i have some feedback? Better ways that I could have written this?

(I do have a lot of idea's once I get into form programming, I am capable now but I want to learn most of the syntax and understand .net before I do anything big.)

Thanks,

pro.


To me, your code looks pretty good, although I haven't searched through it line by line.

This is a link to a post with a bunch of programming ebooks, I think you'd benefit from "C# in Detail". Also, there's one on data structures and algorithms, which will help you out if you're interested in things such as security:
You must login or register to view this content.

Also, if you're still in the "learning" or "beginning" phase, it might be helpful to have a beginners tutorial. I found this one to be really great, and its where I first learned:
You must login or register to view this content.

The following user thanked Epic? for this useful post:

XxprokillahxX
06-14-2011, 06:18 AM #3
Originally posted by AsianInvasion View Post
To me, your code looks pretty good, although I haven't searched through it line by line.

This is a link to a post with a bunch of programming ebooks, I think you'd benefit from "C# in Detail". Also, there's one on data structures and algorithms, which will help you out if you're interested in things such as security:
You must login or register to view this content.

Also, if you're still in the "learning" or "beginning" phase, it might be helpful to have a beginners tutorial. I found this one to be really great, and its where I first learned:
You must login or register to view this content.


Thanks mate i will definitely read, my C++, java and vb.net knowledge has made C# very quick to learn, i am now on the exception handling topic of my book, so this program is only a fraction of my C# knowledge, it was more of a test to see if i could write a full program without references.

EDIT: Tweaked the text, changed the loop a bit to make it more readable.

Thanks again,

Pro
Last edited by XxprokillahxX ; 06-14-2011 at 08:48 AM.

The following user thanked XxprokillahxX for this useful post:

Epic?
06-14-2011, 04:29 PM #4
kiwimoosical
Bounty hunter
Name variables that you know your not going to re-assign const:
    const double PI = Math.PI;


This is the proper way to exit:
    Environment.Exit();


Or you could change the condition of the while loop to be something like while(!str.Equals("exit")) blah..

The following 2 users say thank you to kiwimoosical for this useful post:

Epic?, XxprokillahxX
06-14-2011, 07:10 PM #5
Epic?
Awe-Inspiring
Originally posted by XxprokillahxX View Post
Thanks mate i will definitely read, my C++, java and vb.net knowledge has made C# very quick to learn, i am now on the exception handling topic of my book, so this program is only a fraction of my C# knowledge, it was more of a test to see if i could write a full program without references.

EDIT: Tweaked the text, changed the loop a bit to make it more readable.

Thanks again,

Pro



Yeah, its looking pretty nice.

Just to make your program a bit cleaner looking, I'd suggest you maybe have it so that after the answer is displayed, it waits for the user, and then clears the screen:

1) Put your instructions in the while loop.
2) After the switch-case put "Console.ReadKey();"
3) After the new "Console.ReadKey();" put "Console.Clear();"

So you're program would now appear as:
    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Multi_Choice_area_s
{
class Program
{
static int Main(string[] args)
{
//Assigning variables
string shape;
double X, Y, Z, PI = Math.PI;

while (true)
{
//Showing user the shapes
Console.WriteLine("Options are: Rectangle, Triangle, Circle, Parallelogram, " +
"Trapezium or exit. \"case insensitive\"");

Console.Write("\nEnter shape: ");
shape = Console.ReadLine();

switch (shape.ToLower()) //Changes input to lower case for comparing
{
case "rectangle":
Console.Write("Length: ");
X = Convert.ToDouble(Console.ReadLine());

Console.Write("Width/Height: ");
Y = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("\nThe area of the {0} is: {1}", shape, X * Y);
break;

case "triangle":
Console.Write("Height: ");
X = Convert.ToDouble(Console.ReadLine());

Console.Write("Base length: ");
Y = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("The area of the {0} is: {1}", shape, (Y / 2) * X);
break;

case "circle":
Console.Write("Radius: ");
X = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("The area of the {0} is: {1}", shape, PI * (X * X));
break;

case "parallelogram":
goto case "rectangle";

case "trapezium":
Console.Write("Height: ");
X = Convert.ToDouble(Console.ReadLine());

Console.Write("Top Length: ");
Y = Convert.ToDouble(Console.ReadLine());

Console.Write("Base Length: ");
Z = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("The area of the {0} is: {1}", shape, (X / 2) * (Y + Z));
break;

case "exit":
return 0; //Couldn't figure any other way to exit/don't know one yet.

//If anything that is not a shape entered - ERROR
default:
Console.WriteLine("ERROR: unknown shape entered, try again");
break;
}
//wait for user to press any key
Console.ReadKey();
//clear the screen (thus giving appearance of restarting the program)
Console.Clear();
}
}
}
}


Of course, you could also add in instructions before the ReadKey() to tell the user to press any key.

From there, my other recommendation would be the same as kiwimoosical, simply declare the double "PI" on a different line as "const" or constant, meaning it never changes:

    const double PI = Math.PI;


If you really wanted to make it look nice, I'd suggest you put each calculation in a different method, although for small math like these, its really not necessary.


As far as your skills, I'd suggest you start developing Windows Form Applications as soon as possible, as you don't see many console programs any more, so making a GUI is most practical. Although, if you have experience with VB.NET it should be fairly easy.

Also, if you wanted to build games, you should check out the XNA framework.


EDIT:

You may also want to implement a wordwrap to your program. You could do it most easily by just breaking the text onto a new line where needed, as there's only one place where needed.

I'd suggest you implement a wordwrap anyways though. Wordwrapping in console applications is somewhat complicated, and very clumsy, however, here are two ways I do it (comments should help you make sense of it):

Way number one:
    
private static string WordWrap(string text, int bufferWidth)
{
// declare "result" to store the result of world wrap
// initialize to nothing/blank
string result = "";

// declare string array "lines" to store each line on console
// initialize to each time the text on console is split by a new line
string[] lines = text.Split('\n'Winky Winky;

// for each line in the console window, do the following...
foreach (string line in lines)
{
// declare the "lineLength" to store the length of each line
// initialize to zero
int lineLength = 0;

// declare string array "words" to store each word
// initialize to each time a space character appears in the console window
string[] words = line.Split(' 'Winky Winky;

// for each word in the console window, do the following...
foreach (string word in words)
{
// if the length of a word, plus the length of the line is greater than or equal to width of the consoel window minus 1 character, do the following...
if (word.Length + lineLength >= bufferWidth - 1)
{
// set result equal to a new line plus whatever was already in result
result += "\n";
//reset lineLength to zero
lineLength = 0;
}
// set result to the word, plus a space, plus whatever was already in it
result += word + " ";

//set lineLength to the length of the word, plus one, plus whatever was already in it
lineLength += word.Length + 1;
}

//set result to a new line, plus whatever was already in it
result += "\n";

}
//return result
return result;

}


You'd then call it as:

    Console.WriteLine(WordWrap("YOUR TEXT HERE", Console.WindowWidth));


Way number two:

Just see You must login or register to view this content..


Although, for both of those, it could be beneficial to simply put them in a new class, or at least it would be beneficial to do that if you were working on a larger program.

Hope this helps
Last edited by Epic? ; 06-14-2011 at 07:37 PM.

The following 2 users say thank you to Epic? for this useful post:

kiwimoosical, XxprokillahxX
06-15-2011, 06:37 AM #6
Originally posted by AsianInvasion View Post
Hope this helps


Thanks once again, i will update the thread in a sec with my editing. Also i was going to use method's but since the equations are so small i thought it would just look messy, use too much space.

With the word wrap i don't really need it now. Also with window's forms i was going to make this as one, but i haven't learnt enough to make the GUI look neat, by using MessageBox's etc. Is there a message box that pop's up that can take user input?

Lastly if you wouldn't mind, think of something i should make with a windows form as a challenge for me, i will do my best to research on parts and try to make it. Then i will upload it and paste source here if you want.

I still haven't learnt enough about window's forms and i don't know anything about exception handling yet.

Thanks again also to kiwi,

pro
06-15-2011, 07:31 AM #7
Epic?
Awe-Inspiring
Originally posted by XxprokillahxX View Post
Thanks once again, i will update the thread in a sec with my editing. Also i was going to use method's but since the equations are so small i thought it would just look messy, use too much space.

With the word wrap i don't really need it now. Also with window's forms i was going to make this as one, but i haven't learnt enough to make the GUI look neat, by using MessageBox's etc. Is there a message box that pop's up that can take user input?

Lastly if you wouldn't mind, think of something i should make with a windows form as a challenge for me, i will do my best to research on parts and try to make it. Then i will upload it and paste source here if you want.

I still haven't learnt enough about window's forms and i don't know anything about exception handling yet.

Thanks again also to kiwi,

pro


Here are two lessons, one will cover building a calculator, the other a basic word processor. Yes, both were written by me (but a long time ago, for a different forum).

Calculator:

First off, create a new Windows Form Application, call it calculator.

I am going to give you all the objects you will drag and drop onto your form, and what properties to modify, see here:

Form1 (just select the form background area)
BackColor: Whatever you prefer
Size: 440, 510
Text: Calculator

Text Box
Name: txtDisplay
Location: 66, 52
Multiline: True
Size: 200, 26
TextAlign: Right

Label
Location: 138, 9
Text: Calculator
Font: Microsoft Sans Serif, Size 16, Bold

Now for the buttons:

Name: btnOne
Font: Microsoft Sans Serif, Size 12, Bold
Location: 66, 159
Size: 49, 40
Text: 1

Name: btnTwo
Font: Microsoft Sans Serif, Size 12, Bold
Location: 143, 159
Size: 49, 40
Text: 2

Here's a fun idea, instead of wasting your time editing every category, use the copy and paste feature. Select a button, copy the button (right click > copy or ctrl + c), and then paste the button (right click > paste or ctrl + v). This will allow you to quickly add the buttons. Now all you have to do is change the name, location, and text.

Name: btnThree
Location: 220, 159
Text: 3

Name: btnFour
Location: 66, 239
Text: 4

Name: btnFive
Location: 143, 239
Text: 5

Name: btnSix
Location: 220, 239
Text: 6

Name: btnSeven
Location: 66, 319
Text: 7

Name: btnEight
Location: 143, 319
Text: 8

Name: btnNine
Location: 217, 319
Text: 9

Name: btnZero
Location: 143, 395
Text: 0

Okay, number buttons are in place. Lets add in the function buttons, same size and font:

Name: btnPlus
Location: 324, 159
Text: +

Name: btnMinus
Location: 379, 159
Text: -

Name: btnMultiply
Location: 324, 239
Text: X

Name: btnDivide
Location: 379, 239
Text: /

Name: btnEquals
Location: 324, 319
Text: =

Name: btnClear
Location: 379, 319
Text: C

Finally we'll add in the decimal point, you'll have to adjust the size of the font (not the button) to make it visible:

Name: btnPoint
Location: 220, 395
Text: .

Whew! That was boring! If its any consolation, I not only had to do this twice, but I also had to write the guide on how to do it.

Hopefully your form now looks like this:

You must login or register to view this content.


Well, here's the code, but lets not just copy and paste, if you have to, its here though:

    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 calculatorv1
{
public partial class Form1 : Form
{
/* This program is currently being powered by a series of "if...then...else" statements, as opposed to a "switch" statement, the code for a switch statement is
* present though, so as to prevent the program from trying to "run twice" and crash the code for the switch statment is commented out, it will be commented out
* in the same way this text is, not the double-forward-slash method. */

double total1 = 0; //sets up totals, total1 will be the current/running value, total2 will be the final value displayed to the user
double total2 = 0;
bool plusButtonClicked = false; //sets up plus/minus button booleans, both set to false
bool minusButtonClicked = false;
bool multiplyButtonClicked = false; //sets up multiply/divide button booleans, both set to false
bool divideButtonClicked = false;

/* string theOperator; */

public Form1()
{
InitializeComponent();
}

private void btnOne_Click(object sender, EventArgs e)
{

txtDisplay.Text = txtDisplay.Text + btnOne.Text;
}

private void btnTwo_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnTwo.Text;
}

private void btnThree_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnThree.Text;
}

private void btnFour_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnFour.Text;
}

private void btnFive_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnFive.Text;
}

private void btnSix_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnSix.Text;
}

private void btnSeven_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnSeven.Text;
}

private void btnEight_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnEight.Text;
}

private void btnNine_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnNine.Text;
}

private void btnZero_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnZero.Text;
}

private void btnClear_Click(object sender, EventArgs e)
{
txtDisplay.Clear();
}

private void btnPlus_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();

plusButtonClicked = true; //changes the plus/addition boolean to true when the addition button is clicked
minusButtonClicked = false;
multiplyButtonClicked = false;
divideButtonClicked = false;
/* theOperator = "+"; */
}

private void btnEquals_Click(object sender, EventArgs e)
{

if (plusButtonClicked == true) //if the plus button is clicked, then add the current total to the user input
{
total2 = total1 + double.Parse(txtDisplay.Text);
}

else if (minusButtonClicked == true) //if the minus button is clicked, then subtract the user input from the current total
{
total2 = total1 - double.Parse(txtDisplay.Text);
}

else if (multiplyButtonClicked == true) //if the multiply button is clicked, then multiply the current total by the user input
{
total2 = total1 * double.Parse(txtDisplay.Text);
}

else if (divideButtonClicked == true) //if the divide button is clicked, then divide the current total by the user input
{
total2 = total1 / double.Parse(txtDisplay.Text);
}

/* switch (theOperator)
* {
* case "+":
* //ADDITION CODE HERE (from the if statement)
* break;
* //add more cases here as needed
* default:
* //DEFAULT CODE HERE (what to do if none of the variables apply to one of the cases)
* break;
* } */

txtDisplay.Text = total2.ToString(); //sets the display text to the value of total2 (that gets converted from a double [number] to a string [text]
total1 = 0; //resets total1 so it can hold more data


}

private void btnPoint_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnPoint.Text;


}

private void label1_Click(object sender, EventArgs e)
{

}

private void txtDisplay_TextChanged(object sender, EventArgs e)
{
}


private void btnMinus_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear(); //sets the total1 to itself + the contents of the textbox (adds user input to current/running total)
plusButtonClicked = false;
minusButtonClicked = true; //changes minus boolean to true when the minus button is clicked
multiplyButtonClicked = false;
divideButtonClicked = false;
/* theOperator = "-"; */

}

private void btnMultiply_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
minusButtonClicked = false;
multiplyButtonClicked = true; //changes the multiply boolean to true when multiply button is clicked
divideButtonClicked = false;
/* theOperator = "*"; */

}

private void btnDivide_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
minusButtonClicked = false;
multiplyButtonClicked = false;
divideButtonClicked = true; //changes the divide boolean to true when the divide button is clicked
/* theOperator = "/"; */

}
}
}


Something you may notice is comments, comments aren't part of the code that is executed, programmers add them in to help us discern what's going on:

You must login or register to view this content.

So, let's add in the variables:

You must login or register to view this content.

Okay we start off with 2 doubles, remember, a double lets us hold partial numbers (numbers that can be whole or can have a decimal point attached). The first is total1, the second is total2.

total1 will be the current total that keeps track as we go, total2 is what will finally be displayed to the user when the user presses enter, its just cleaner this way

We then have a bunch of booleans, remember, booleans can be true or false. We have a boolean for each button of plus, minus, multiply, and divide, when we click on a button, we'll change one of these to true (depending on the button). Currently they're set to false to keep the calculator from executing everything immediately then crashing.

Up next we'll add in the code for our numerical buttons. We'll start with 1 and work our way up to 9, then do 0. The code for the buttons more or less look the same.

Double click the button 1 (btnOne) to get at the code stub.

Here's the code for the button 1:

You must login or register to view this content.

We're taking the text display (the textbox) and looking at the text currently in it. Then we add the text display to the text in the numerical button that was just pressed.

Think of it as:
The text in text display = itself + the text on a numerical button

This way we keep what was in the text display, instead of just overwriting it.

If we entered 2 into it and then pressed 1, we want to get 21, not 1, that's why we have to set it equal to itself.

Text is a property (which we defined in the properties menu at the beginning). Remember that? Well this is how it looks in code. We have to put the full stop (that's the proper name, its actually a period) in between the object (txtDisplay) and Text to indicate that its a built in property of txtDisplay.

If that confused you, don't worry to much, you'll get it eventually.

Now with that you can figure out all the other numerical buttons (remember to double click the button to get at the code).

If you're having issues, here's the code:

You must login or register to view this content.

Now that all our numbers work, press File > Save All. Go into debug mode (run the program) and test it out, when you press number buttons, numbers should appear in the text box.

Okay, let's make our clear button do some work!

Its very easy, really, you can do it with one line of code:
You must login or register to view this content.

Its hard to not understand it. Your basically using a method (a method is basically a command) that is already built (by C#) called clear. You're telling the textDisplay (text box) to clear itself. Test it out, go into debug mode and you'll see that it clears the text box.

So, now all we need to do is well... math! OF COURSE! The most important part of the calculator. Without math its just a box with numbers that can clear itself.

Well this is where it gets tricky. We're going to be using something called conditional logic. I have a whole lesson planned (right after this project) dedicated to conditional logic that will take it in much greater detail, but for now, think of conditional logic as if statements.

What is conditional logic? Conditional Logic is something that executes itself in a logical way should a certain condition be met.

What is an if statement? An if statement has three parts, if, then, else. If statements begin with if, asking if a condition has been met. If it has THEN then some code gets executed. If it hasn't been met, then do "else" or what to do if the condition wasn't met.

We'll really only be using the if/then part for the calculator.

Let's start by adding in the code for the addition button, double click the addition button to get at the code:

You must login or register to view this content.

So, what we're doing is setting total1 to equal itself plus whatever was in the txtDisplay. We use the command double.Parse() to parse into the double variable. Parsing it just takes the text (because we enter text into the text box, even if its a number we put in) and converts it to a double variable (so it can be used to do math).

We're adding two things, the current value of total1 and the value in the txtDisplay.

We set our variables to false with the exception of the plusButtonClicked, because the plus button was clicked!

We will eventually use these variables to make our final calculation in the equals button, but until that point, we need to add in our other operator buttons.

Here's the code for the minus button:

You must login or register to view this content.

Notice what's changed? Well, the minusButtonClicked boolean variable! So that means, for the multiply and divide buttons, all you need to change is the boolean variable!

But first, let me draw your attention to txtDisplay.Clear();
This will clear what's in the text box so a new "fresh" number can be entered.

The total1 = total1 + double.Parse(txtDisplay.Text); saves the value though, that way we're not just clearing everything we have entered so far, we're clearing it, and saving it, to be equated later.

So go ahead, add in the code for the multiply and divide buttons on your own! Remember to change the boolean variable!

What's left? The point (decimal point) button, and the equals button.

Let's throw the point button in real quick, and save the equals button for last.

Here's the code for the point button (double click point button to get at the code stub - although do I really need to say that every time?):

You must login or register to view this content.

Its very easy. We just take the text on the point button (which happens to be a point) and add it to the txtDisplay. Simple. As. That.

Okay, we have everything functioning except for the fact we can't calculate anything yet....

Get at that equals button code! Here we go:

You must login or register to view this content.

HOLY CONDITIONAL LOGIC

Wow, now that's an if statement.

Let's break it down.

We start with the plus button in our if statement, we're testing if the plusButtonClicked boolean variable has the value of true (remember, it only does when the plus button is clicked).

If that condition is true, then we execute the code beneath it between the curly brackets {}

total2 = total1 + double.Parse(txtDisplay.Text);

Well, I told you total2 is going to be the final answer display.
So we set the final answer display to total1.

We add total1 to txtDisplay for our final total2 answer.

What follows that is the else if statements.

Else if basically says, well if that wasn't true (else) then we have to do something else (else). Well, here's that else, is this true (if)?

Okay, I realize that made no sense, here's what I'm trying to say:

If the condition above isn't true we have to do something else. We can't just assume that if the plus button wasn't clicked we need to subtract immediately, so we have to check if the minusButtonClicked boolean is true, which would indicate that the minus button was clicked.

If so, then we set up total2 to be the value of the text in the text box subtracted from the value of total 1.

We go on and on like that, for multiply and divide. We check if the boolean was activated (true) or not, if so, then we execute the code for multiplying or dividing, and if not, we move to the next else if statement.

So go ahead and program that in.

Save All then debug your program. Something's missing...
The equals button still isn't working!

We need to add in one more piece of code:

You must login or register to view this content.

This tells the equals button that when its clicked it needs to display whatever the value of total2 is, then clear total1 (set total1 to zero) so it can take in more user input again.

You should now have a working, fully functioning, bug-free calculator.

Test it out, Save All, debug. Does it work? It should. If not, see where I posted the full code.

Here are some things you can try with your calculator:

  • Divide by Zero
  • Type numbers directly into box
  • Do multiple step math (1+1+1 instead of 1+1)
  • Try to go into negative numbers


So you'll notice if you divide by zero, its not quite right, the answer isn't infinity, but it'll have to do for now (its undefined, for those of you who didn't know).

Having fun yet?


Word Processor:

So, this Project we will be creating a basic word processor. Okay, correction, technically its more of a text editor, even though they're pretty much the same.

Things you should understand before going forward: Variables, Aspects of Windows Forms, Conditional Logic, and really any other things we've covered so far!


Now this really won't be too hard, in fact, at least time-wise, it should be relatively easy.

We're going to create a word processor/text editor with the following specifications:


  • MenuStrip (menu bar)
  • Open .txt and .doc files using Open File Dialog
  • Save files in .txt format using Save File Dialog
  • Close/Quit Application (from MenuStrip) with Homemade Dialog
  • Edit section of StripMenu featuring Copy, Paste, and Clear features
  • A Rich Text Box that is large and can be used to edit/create text-based files


So we should now hopefully have a basic idea of what we are creating. If you read the Aspects of Windows Forms lesson, you should already have an idea of what all that is, so I won't explain it again.

Start by creating a new project, make sure its a Windows Form Application, call it "basicwordprocessor".

When you are taken to the form edit mode, expand the form to a proper size (so that someone could do work inside of it).

Place a MenuStrip object on your form, it should automatically cover the top area.

Place a Rich Text Box in the center of your form, enlarge the Rich Text Box so it takes up most of the form, that's the main object.

Add on to the MenuStrip. In the box where it says "Type Here" enter in "File", next to that box (once you enter File) another box directly to the right will appear, enter in "Edit"

Under the File tab add in the following sections:
Open
Save
*insert a separator*
Quit

Under the Edit tab add in the following sections:
Copy
Paste
*insert a separator*
Clear

Your form should now look something like this:
You must login or register to view this content.

Under each tab you should have what I instructed (Open Save -separator- Quit and Copy Paste -separator- Clear).

Now, that's everything we'll need, actually, with the exception of two things. Let's add them in real quick.

Go under Dialogs in your toolbox and drag in an Open File Dialog and a Save File Dialog, it shouldn't add anything except to near the bottom of your page next to the MenuStrip.

Let's rename some of our objects to make it a little more clear.


  • Rename the rich text box to txtBox
  • Rename the Open File Dialog to openFD
  • Rename the Save File Dialog to saveFD
  • Select the "File" in the MenuStrip, change the text property to have an ampersand (&Winky Winky in front of it (so it looks like "&File"). That will underline it.
  • Add the ampersand in front of the text property of the following objects: Open, Save, Quit, Edit, Clear.





Okay, time to jump into the code!

Here is the code for the entire project, do not just copy and paste, its extremely lame, its just for reference purposes:

    
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 basicwordprocessor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
// Open file to the Rich Text Box

string Chosen_File = "";

#region properties
openFD.InitialDirectory = "C:";
openFD.Title = "Open a Text File";
openFD.FileName = "";
openFD.Filter = "Text Files|*.txt|Word Documents|*.doc";
#endregion

if (openFD.ShowDialog() != DialogResult.Cancel)
{
Chosen_File = openFD.FileName;
txtBox.LoadFile(Chosen_File, RichTextBoxStreamType.PlainText);
}

}

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
// Save file from text in Rich Text Box into .txt format

string Save_File = "";

#region properties
saveFD.InitialDirectory = "C:";
saveFD.Title = "Save a Text File";
saveFD.FileName = "";
saveFD.Filter = "Text File|*.txt";
#endregion

if (saveFD.ShowDialog() != DialogResult.Cancel)
{
Save_File = saveFD.FileName;
txtBox.SaveFile(Save_File, RichTextBoxStreamType.PlainText);
}
}


private void quitToolStripMenuItem1_Click(object sender, EventArgs e)
{

// Closes program

if (txtBox.Text != "")
{
if (MessageBox.Show("Are you sure you want to quit?", "Close", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)
{
Application.Exit();
}
}
else
{
Application.Exit();

}
}

private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
// Clears text buffer
txtBox.Clear();
}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{

// Copies selected text to Clipboard

if (txtBox.SelectionLength > 0)
{
txtBox.Copy();
}
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{

// Pastes text that was on Clipboard

if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{
txtBox.Paste();
}

}

}
}


Okay folks, let's do the standard: code chunk then break down.

Let's start by adding in the code for our Open option in the MenuStrip. Double click the Open to get at the code stub.

Add in the following code:
You must login or register to view this content.

Let's talk about it. We start with a comment, telling us this will open the file to the Rich Text Box.

We start by creating an empty string variable called Chosen_File.

Then we have something new, a region. A region is just to block off a chunk of code, to make the program more readable.
Let me demonstrate.

When you enter into the region you can put in code, it will run normally, the region doesn't actually change the program at all.

The region can be minimized by clicking the minus button to the left:
You must login or register to view this content.

When minimized it "compacts" the code, so its easier to view the program:
You must login or register to view this content.

Now all the code we entered in the properties region is in that little box, we can click the + next to the box to open it up and get at the code.

Regions are always within "region tags":
#region begins the region
#endregion ends the region

What you put to the right of #region will be the title/name of the region. You can put anything there, since in this case we're putting properties there, we decided to name it properties.

Within the region we have properties of openFD (our Open File Dialog). Remember anything that has a full stop (period) followed by the name of a property, is, well, a property!

We start by defining the property InitialDirectory, this is exactly what it sounds like. We're telling the program where to start looking for files. When you open the Open File Dialog it will jump to a folder automatically, so by putting in C: we're telling it to start in the C drive folder.

We then have the Title (which is as always the top part of the program/dialog next to the minimize/maximize/close buttons). We set that to Open a Text File.

Then we set the file name to blank.
See how when I open a new file the "File name" field is blank:
You must login or register to view this content.

That's what we're leaving blank.

Finally we have the filter, this filters what types of files it can open, ours can open text files (.txt) and word document files (.doc). We define the "name" of the file (basically what it will display to the user under the Types of Files section) and then we have a line (|) which you can create by pressing shift + back-slash. Then we have the file extension, that is what tells the program which files to filter (the name could be anything, you need the extension to actually filter it).

We then have another line and then the appropriate entry for opening a word doc file.

That ends our properties region, now we move on to some conditional logic in the form of an if statement.

In the if statement we're going to test if the ShowDialog property of openFD is not equal to DialogResult.Cancel. This is pretty much asking if the user pressed cancel or not.

If the user didn't press cancel, then we move on to our code.

We set the variable Chosen_File to the FileName property of openFD, and we set the txtBox (the rich text box) LoadFile property to load the variable "Chosen_File" which is the name of a file. This basically loads the file into the Rich Text Box.

We then have the RichTextBoxStreamType.PlainText. This is a parameter, you'll learn easier ways to load text later, but for now, this will do. This basically tells the Rich Text Box to load the Plain Text.

That ends our code for the open button!


Shall we move on?


Now we're going to add our save button function.

Double click the Save feature and let's get to work.

Add this code:
You must login or register to view this content.

Yep, very similar to the Open option. We change the variable to Save_File. The properties are a bit different. We use saveFD (our Save File Dialog) instead of openFD. We change the if statement slightly. The key is we're using the SaveFile instead of LoadFile property of the Rich Text Box.

So that's easy.

Now let's pop in and do our close program code.

All we need is to double click the Quit, and then add in:

Application.Exit();

Let's make it a bit fancier. Let's make a dialog asking them if they really want to quit, but let's only do that if there is text in the rich text box, otherwise we can just close it without any trouble.

Here's the code:
You must login or register to view this content.

We basically use an if statement, it says:
if txtBox's Text Property is not equal to nothing/blank, open the message box, if else (if it is blank) then just go ahead and exit.

The message box code starts with the text parameter, the title parameter, the buttons on the message box, then the icon that will appear with the text in the message box.

Not super difficult...

Let's add the clear feature, double click the Clear to get at the code.
Now add in this one line:
You must login or register to view this content.

Not to tough either, uses the Clear method of txtBox to clear itself. We use a comment saying "Clears text buffer" because technically speaking its a text buffer, don't worry to much about technical terms. I'll cover them more when we build our text-based game.

Time to add our copy and paste buttons...

Click the copy first.

We're going to use the copy method of the rich text box:
You must login or register to view this content.

We put it in an if statement to make sure the user has selected (highlighted) an area greater than nothing (they've highlighted at least one color).

Last but not least.... The Paste option.

This pastes text that was on the clipboard.

Here's the code:
You must login or register to view this content.

Our if statement reads:

if the clipboard has text on it, then use the rich text box method of paste to paste the text into the rich text box.

Simple as that!

Save All, Build, Debug Mode (save and run the program), it should be working!

Things to test:

  • Open
  • Save
  • Quit
  • Copy
  • Paste
  • Clear
  • In the actual code try to use the region to minimize parts of your code!


It should be good! Nice job!

Let's make one last adjustment. Go back into the Form editing mode (the visual/design editor).

Click Open under File on your Form.
Look in the Property Manager for ShortcutKeys.
Click the down arrow next to the box and select the Modifier Ctrl and the Key "O". This will add a Ctrl + O next to your Open, and make it so that shortcut opens the Open File Dialog.

Add in the following shortcuts:
Save Ctrl + S
Quit Ctrl + Shift + Q
Copy Ctrl + C
Paste Ctrl + V
Clear Ctrl + Alt + C

There you go, now that's looking nice. Test out those shortcuts!

That concludes this project, I hope you enjoyed it!


Hopefully, you like these two lessons/projects I put together. Since the forum I originally posted to spends a lot of time offline these days, I might just post the rest of my lessons on here, which takes one up to developing a game.

As far as message boxes that take stuff in, they can only take in button input. I'd suggest you just make a new form, put whatever you want on there, and do something like:
    Form2 form = new Form2;
form.Show();


That will open up the second form.

Or, you can base user input off of buttons.

For the message box, you have:

    MessageBox.Show("Your body text", "Your title text", MessageBoxButtons.*buttons*, MessageBoxIcon.*icon*);


Of course, you'd want to replace the body/title text with whatever text you want. You'd also want to replace *buttons* with whatever button(s) you want, and *icon* with whatever icon you want to appear in your message box.

Hope this helps!

EDIT:
I just realized the first lesson/project (calculator) I gave you, is super nooby, but if you just browse the pictures and code, you'll get the idea. Its nooby because it my previous series of lessons, I think it was like lesson 4, so we'd just barely gotten into it.

SECOND EDIT:
If you're looking for a challenge, recreate the viewbot I just released: You must login or register to view this content.
The code itself is very easy, and you don't have to build it the same way I did, however it does use a bunch of different controls (objects on GUIs are controls). Also, there are a lot of properties that you change from the property editor, so it will give you good experience with that.
Hint: I used the browser control to navigate to webpages, the timer to refresh the browsers, and you can fill in the rest.

I'd suggest building the viewbot, because its not excessively hard, its code that most people will be familiar with, and it is very GUI-design intensive, and really demonstrates building GUIs more than actual complex coding, which is actually quite nice if you're working on GUIs.
Last edited by Epic? ; 06-15-2011 at 07:40 AM.

The following user thanked Epic? for this useful post:

XxprokillahxX
06-15-2011, 07:46 AM #8
Originally posted by AsianInvasion View Post
I'd suggest building the viewbot, because its not excessively hard, its code that most people will be familiar with, and it is very GUI-design intensive, and really demonstrates building GUIs more than actual complex coding, which is actually quite nice if you're working on GUIs.


I will do each one, even the calculator for practise :P i will post updates on my O.P with a multi-page.

Love the viewbot challenge will really get me thinking, plus i won't forget anything afterwards.

EDIT: i don't know anything about browser control etc. so that will be the hard part for me, have not learnt any of that yet.
06-15-2011, 07:52 AM #9
Epic?
Awe-Inspiring
Originally posted by XxprokillahxX View Post
I will do each one, even the calculator for practise :P i will post updates on my O.P with a multi-page.

Love the viewbot challenge will really get me thinking, plus i won't forget anything afterwards.

EDIT: i don't know anything about browser control etc. so that will be the hard part for me, have not learnt any of that yet.



Yeah, considering I built the view bot, I'm pretty familiar with its code. The browser itself is effectively Internet Explorer loaded into a control (well, actually, that's exactly what it is). The methods are straight forward:
webBrowser.Navigate("URL");
webBrowser.Refresh();

I won't give away any more than that unless you ask specifically, but its pretty obvious how the rest of it factors in.

Really, the key to making GUIs is understanding the properties in the Property Manager - at least for building small GUI projects (such as a view bot). The code that gives it functionality is extremely easy.
06-15-2011, 08:25 AM #10
Originally posted by AsianInvasion View Post
Yeah, considering I built the view bot, I'm pretty familiar with its code. The browser itself is effectively Internet Explorer loaded into a control (well, actually, that's exactly what it is). The methods are straight forward:
webBrowser.Navigate("URL");
webBrowser.Refresh();

I won't give away any more than that unless you ask specifically, but its pretty obvious how the rest of it factors in.

Really, the key to making GUIs is understanding the properties in the Property Manager - at least for building small GUI projects (such as a view bot). The code that gives it functionality is extremely easy.


I won't ask for any more help unless i logically cannot understand it or find it. I am just about finished calculator, it will take time as i am reading over it to understand it while i write, even though it is basic. Very true about property manager, i have an idea on how to make it anyway, but i am going to code them in order.

I will get back to when im done or if i really need help. Till then, you have been great help!

EDIT: updated with text editor and calculator

pro
Last edited by XxprokillahxX ; 06-15-2011 at 09:39 AM.

The following user thanked XxprokillahxX for this useful post:

Epic?

Copyright © 2024, NextGenUpdate.
All Rights Reserved.

Gray NextGenUpdate Logo