C# can't use variable from IF statement - c#

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
{
}
}
}
}

Related

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

Need to calculate when adding coin

I am building a vending machine and I am stuck on adding coins.
Coin should automatically be calculated when I click on the assigned button But Instead I am just getting the value inside textbox here's 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 VendingMachine
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void operator_Click(object sender, EventArgs e)
{
new Form2().Show();
this.Hide();
}
private void fiveP_Click(object sender, EventArgs e)
{
balance.Text = ((double)balance.Text + 0.05).ToString();
}
private void tenP_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "0.10";
}
private void twentyP_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "0.20";
}
private void fiftyP_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "0.50";
}
private void onePound_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "1.00";
}
private void twoPound_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "2.00";
}
}
}
Coin Class
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace VendingMachine
{
[Serializable]
internal class Coin : ISerializable, IComparable
{
public string coinName = "";
public double coinValue = 0.0;
public int coinBalance = 0;
public string Name
{
get { return this.coinName; }
set { this.coinName = value; }
}
public double Value
{
get { return this.coinValue; }
set { this.coinValue = value; }
}
public int Balance
{
get { return this.coinBalance; }
set { this.coinBalance = value; }
}
public Coin(string coin_name)
{ this.coinName = coin_name; }
public Coin(SerializationInfo info, StreamingContext ctxt)
{
this.coinValue = (double)info.GetValue("CoinValue", typeof(double));
this.coinName = (string)info.GetValue("CoinName", typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("CoinValue", this.coinValue);
info.AddValue("CoinName", (object)this.coinName);
}
public int CompareTo(object obj)
{
if (obj is Coin)
return this.Value.CompareTo(((Coin)obj).Value);
else
throw new ArgumentException("object is not a Coin");
}
public static IComparer sortByCoinName()
{
return (IComparer)new Coin.sortByCoinNameHelper();
}
private class sortByCoinNameHelper : IComparer
{
int IComparer.Compare(object a, object b)
{
return ((Coin)a).Name.CompareTo(((Coin)b).Name);
}
}
}
}
if balance is the textbox you are working with, you are clearing it with the button press, erasing whatever was in it prior to the button press, so it will always be "" + whatever. also, you can't add strings like that, "1.00" + "2.00" == "1.002.00", != "3.00"
You are adding strings rather than numbers. You'll need to convert your strings into numbers to add them together, and you shouldn't clear your results first.
For example:
private void fiveP_Click(object sender, EventArgs e)
{
// balance.Clear(); <- You don't need this.
balance.Text = ((double)balance.Text + 0.05).ToString();
}
that is because you are using a string type for calculating.. there is a difference between calculating something and displaying it. in short:
float value = 0;
void print()
{
balance.Text = string.Format("{0:0.00}", value);
}
private void fiveP_Click(object sender, EventArgs e)
{
value += 0.05f;
print();
}
private void tenP_Click(object sender, EventArgs e)
{
value += 0.10f;
print();
}
private void twentyP_Click(object sender, EventArgs e)
{
value += 0.20f;
print();
}
private void fiftyP_Click(object sender, EventArgs e)
{
value += 0.50f;
print();
}
private void onePound_Click(object sender, EventArgs e)
{
value += 1;
print();
}
private void twoPound_Click(object sender, EventArgs e)
{
value += 2;
print();
}
in your code you are not adding numbers, example:
you have this code:
private void tenP_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "0.10";
}
the value of balance.Text = "0.10"
then, if the next code is executed:
private void fiftyP_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "0.50";
}
the value of balance.Text = "0.50"
the point is that your are trying to add strings not numbers and you are clearing your previous value

Text property not changing?

What is happening is, even though the questionNr is set to 1, it's not changing the .Text properties of ans1-4, as well as the questionLabel. Any help would be appreciated. Also as a sub-question, is it possible to do something along the lines of if(ans1.Clicked = true)?
public partial class Form1 : Form
{
int pointCounter = 0;
private SoundPlayer _soundPlayer;
int questionNr = 1;
public Form1()
{
InitializeComponent();
_soundPlayer = new SoundPlayer("song.wav");
}
private void pictureBox1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://www.amazon.com/Chuck-Seasons-One-Five-Blu-ray/dp/B007AFS0N2");
}
private void Form1_Load(object sender, EventArgs e)
{
_soundPlayer.PlayLooping();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void muteButton_Click(object sender, EventArgs e)
{
if (muteButton.Text == "Mute")
{
muteButton.Text = "Unmute";
_soundPlayer.Stop();
}
else
{
muteButton.Text = "Mute";
_soundPlayer.PlayLooping();
}
}
private void playButton_Click(object sender, EventArgs e)
{
ans1.Visible = true;
ans2.Visible = true;
ans3.Visible = true;
ans4.Visible = true;
playButton.Visible = false;
}
public void question()
{
if (questionNr == 1)
{
questionLabel.Text = "What is Chuck's full name?";
ans1.Text = "Charles Irving Bartowski";
ans2.Text = "Charles Richard Bartowski";
ans3.Text = "Charles Luke Bartowski";
ans4.Text = "Zachary Strahovski";
}
}
private void ans1_Click(object sender, EventArgs e)
{
}
private void ans2_Click(object sender, EventArgs e)
{
}
private void ans3_Click(object sender, EventArgs e)
{
}
private void ans4_Click(object sender, EventArgs e)
{
}
}
}
Form where you invoke the question() method. First call that method from where you need.
eg: FormLoad/Button click etc..Then try
public Form1()
{
InitializeComponent();
_soundPlayer = new SoundPlayer("song.wav");
question();
}
It's good if you put a break point in your Form Load event and see how your code executed.Then you'll get an idea about the flow of your code.

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

Trying to write a simple calculator... beginner with C#, can't get past an exception

Okay, so I am modeling this idea off of one of my school projects I had fairly recently and I am not sure why it isn't working at the moment.
My current plan for the program is to use a DataManager to hold a string array containing the numbers a user would input from the menu, and then convert them into integers, and ultimately delineate through them by operators and such. I haven't figured out the last part, and I don't think that idea is going to work like I made it sound. But right now I am having trouble getting the program to store string values in the array.
When I run the program my current goal is to click '1' and press 'Enter', when that happens I want the output to look like 'Number: 1' but I keep throwing an exception.
"An unhandled exception of type 'System.InvalidCastException' occurred in mscorlib.dll
Additional information: At least one element in the source array could not be cast down to the destination array type."
Here is the code from my DataManager class....
public class DataManager
{
public ArrayList calculation;
public DataManager()
{
calculation = new ArrayList();
}
public void addNumbers(string n)
{
calculation.Add(n);
}
// public NumbersAndOperators[] getNumbers()
//{
// return //(NumbersAndOperators[])calculation.ToArray(typeof(NumbersAndOperators));
//}
public void removeNumbers(NumbersAndOperators n)
{
calculation.Remove(n);
}
public void addOperators(string o)
{
calculation.Add(o);
}
public NumbersAndOperators[] getOperators()
{
return (NumbersAndOperators[])calculation.ToArray(typeof(NumbersAndOperators));
}
public void removeOperators(NumbersAndOperators o)
{
calculation.Remove(o);
}
}
}
Here is the code from my NumbersAndOperators class
public class NumbersAndOperators
{
private string number; private string operate;
public NumbersAndOperators(string n, string o)
{
number = n;
operate = o;
}
public void setNumber(string n)
{
number = n;
}
public void setOperate(string o)
{
operate = o;
}
public string getNumber(string n)
{
return n;
}
public string getOperate(string o)
{
return o;
}
}
}
Here is the code from my form
public partial class Form1 : Form
{
public DataManager data;
public Form1(DataManager d)
{
InitializeComponent();
data = d;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button10_Click(object sender, EventArgs e)
{
string n = "0";
data.addNumbers(n);
}
private void button1_Click(object sender, EventArgs e)
{
string n = "1";
data.addNumbers(n);
}
private void button2_Click(object sender, EventArgs e)
{
string n = "2";
data.addNumbers(n);
}
private void button3_Click(object sender, EventArgs e)
{
string n = "3";
data.addNumbers(n);
}
private void button4_Click(object sender, EventArgs e)
{
string n = "4";
data.addNumbers(n);
}
private void button5_Click(object sender, EventArgs e)
{
string n = "5";
data.addNumbers(n);
}
private void button6_Click(object sender, EventArgs e)
{
string n = "6";
data.addNumbers(n);
}
private void button7_Click(object sender, EventArgs e)
{
string n = "7";
data.addNumbers(n);
}
private void button8_Click(object sender, EventArgs e)
{
string n = "8";
data.addNumbers(n);
}
private void button9_Click(object sender, EventArgs e)
{
string n = "9";
data.addNumbers(n);
}
private void division_Click(object sender, EventArgs e)
{
string o = "/";
data.addOperators(o);
}
private void multiplication_Click(object sender, EventArgs e)
{
string o = "*";
data.addOperators(o);
}
private void subtraction_Click(object sender, EventArgs e)
{
string o = "-";
data.addOperators(o);
}
private void addition_Click(object sender, EventArgs e)
{
string o = "+";
data.addOperators(o);
}
private void dec_Click(object sender, EventArgs e)
{
string n = ".";
data.addNumbers(n);
}
private void equals_Click(object sender, EventArgs e)
{
panel1.Controls.Clear();
NumbersAndOperators[] num = data.getNumbers();
Label tmp;
for (int i = 0; i < num.Length; i++)
{
tmp = new Label();
tmp.Text = "Number:" + data.getNumbers();
tmp.AutoSize = true;
tmp.Location = new Point(0, 85);
panel1.Controls.Add(tmp);
}
}
}
}
I appreciate any and all advice, this is a problem I haven't seen before which makes it even harder to understand from just reading. I've been googling like a fool for awhile now and everything that comes up I simply do not understand.
Also, I Commented out the line that is throwing the exception
When you call:
public void addNumbers(string n)
{
calculation.Add(n);
}
you add a string to your ArrayList.
When you call:
(NumbersAndOperators[])calculation.ToArray(typeof(NumbersAndOperators));
It tries to retrieve data as NumbersAndOperators, which is invalid since you added string to your ArrayList.
Best would be to have your calculation member as:
public List<NumbersAndOperators> calculation;
so you have a type safe list.
On this line:
return (NumbersAndOperators[])calculation.ToArray(typeof(NumbersAndOperators));
You're trying to get an array of NumbersAndOperators, but your ArrayList also contains strings, and strings can't be cast to NumbersAndOperators...
I guess you meant to write:
for (int i = 0; i < num.Length; i++)
{
tmp = new Label();
tmp.Text = "Number:" + num[i]; // <--
tmp.AutoSize = true;
tmp.Location = new Point(0, 85);
panel1.Controls.Add(tmp);
}

Categories