C# Adding a value to a variable when clicking a button - c#

So, huh, I'm kinda new to programming in general and I have a questions that maybe you could help me out. I don't know if I did this right but hope you can give me a light here.
public partial class Form1 : Form
{
private int tick;
private int conta_jogadas;
private string[,] grelha = new string[3,3];
public Form1()
{
InitializeComponent();
}
private void pos00_button_Click(object sender, EventArgs e)
{
if (tick == 0)
{
pos00_button.Text = "X";
tick = 1;
}
else if (tick == 1)
{
pos00_button.Text = "O";
tick = 0;
}
grelha[0, 0] = pos00_button.Text;
conta_jogadas++;
}
And to verify it I have:
private void Form1_Load(object sender, EventArgs e)
{
if (conta_jogadas == 1)
{
MessageBox.Show("Teste");
}
}
For the moment I just want my button to add 1 to my variable. If i click it 3 times, my conta_jogadas will be = 3. I think I was clear here, don't know what else I can add to help. Well, thanks in advance guys.

This function
private void Form1_Load(object sender, EventArgs e)
{
if (conta_jogadas == 1)
{
MessageBox.Show("Teste");
}
}
Will execute exactly once, when your form loads. At that time the variable conta_jogadas will have the value 0 (The default for an int) so you will not ever see your message box.
You could change this to a normal function that you call whenever you update conta_jogadas if you want to see the message box when the value becomes 1

For the moment I just want my button to add 1 to my variable. If i click it 3 times, my conta_jogadas will be = 3.
Try this:
public partial class Form1 : Form
{
private int tick;
private int conta_jogadas;
private string[,] grelha = new string[3,3];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (conta_jogadas == 1)
{
MessageBox.Show("Teste");
}
}
private void pos00_button_Click(object sender, EventArgs e)
{
conta_jogadas++;
grelha[0, 0] = pos00_button.Text;
}
}
Every time button: pos00 gets clicked, variable conta_jogadas gets 1 added to the current number.
Note: couldn't compile since, I don't have Visual Studio installed here...

Related

Increment a number on page load in a windows form. in c# for Visual studios 2015

This is what i currently have but it only changed the label to 1 and when i close the page but not the application and then re load the page it is still at 1.
Any help here would be amazing, thanks.
//Form 1
public partial class BasketScreen : Form
{
private void PurchaseButton_Click(object sender, EventArgs e)
{
// show the purchase products screen.
this.Hide();
PurchaseScreen ps = new PurchaseScreen();
ps.Show();
}
}
//UniqueNumber is the number i wish to display.
//OrderNumber is the name of the label where i want to display the UniqueNumber
//form 2
public partial class PurchaseScreen : Form
{
//private int UniqueNumber = 0; This was the issue
//This line was the fix.
private static int UniqueNumber = 0;
}
private void PurchaseScreen_Load(object sender, EventArgs e)
{
UniqueNumber++;
OrderNumber.Text = UniqueNumber.ToString("000");
}
private void BackButton_Click(object sender, EventArgs e)
{
this.Hide();
BasketScreen bs = new BasketScreen();
bs.Show();
}

Create one loading form and load different form

I have created one loading form, but I want access the loading form and load the different form. I know there is a way to achieve this, but the way that I think is create another loading form and access that another loading form to load the different form, even though the loading form contents are same.
How can I achieve this?
Here is the code of Loading Form:
public Loading()
{
InitializeComponent();
this.timer1.Interval = SystemManager.RandomNumberGenerator(1000, 2000);
this.timer1.Tick += new EventHandler(this.CheckTimer);
}
private void Loading_Load(object sender, EventArgs e)
{
this.timer1.Start();
}
private void CheckTimer(object sender, EventArgs e)
{
uint timeLeft = 1;
timeLeft--;
if (timeLeft == 0)
{
this.timer1.Stop();
this.Hide();
AgeConfirmation _ageConfirmation = new AgeConfirmation();
_ageConfirmation.ShowDialog();
this.Close();
}
}
Above code is one loading form and load another form by the time is reached 0.
I have tried like this:
public class SystemManager
{
public static void LoadForm(Form _form = null, Form _loadForm = null)
{
_form.Hide();
_loadForm = new Form();
_loadForm.ShowDialog();
_form.Close();
}
}
and access it like this:
SystemManager.LoadForm(this, AgeConfirmation);
But it is throws the following error:
'System.Windows.Forms.AgeConfirmation' is a 'type' but is used like a 'variable'
My Question is: Create only one form (Loading Form), and access that Loading Form and by the time, the time reached 0, it will access different form.
Your answer much appreciated!
Thank you very much!
You should be using _ageConfirmation, which is the form object, not AgeConfirmation which is the form type.
i.e. SystemManager.LoadForm(this, _ageConfirmation);
Solved by myself! I create a getter and setter int value and by using switch case and the code will be like this:
public class UserInformation
{
public static int Value
{
get;
set;
}
}
public partial class Loading : Form
{
public Loading()
{
InitializeComponent();
this.timer1.Interval = SystemManager.RandomNumberGenerator(1000, 2000);
this.timer1.Tick += new EventHandler(this.CheckTimer);
}
private void Loading_Load(object sender, EventArgs e)
{
this.timer1.Start();
}
private void CheckTimer(object sender, EventArgs e)
{
uint timeLeft = 1;
timeLeft--;
if (timeLeft == 0)
{
this.timer1.Stop();
this.Hide();
switch (UserInformation.Value)
{
case 0:
AgeConfirmation _ageConfirmation = new AgeConfirmation();
_ageConfirmation.ShowDialog();
break;
case 1:
MainForm _mainForm = new MainForm();
_mainForm.ShowDialog();
break;
case 2:
Event _event = new Event();
_event.ShowDialog();
break;
}
this.Close();
}
}
}
private void AgeConfirmation_Load(object sender, EventArgs e)
{
UserInformation.Value = 1;
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Loading _loading = new Loading();
_loading.ShowDialog();
this.Close();
}
private void MainForm_Load(object sender, EventArgs e)
{
UserInformation.Value = 2;
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Loading _loading = new Loading();
_loading.ShowDialog();
this.Close();
}
By the time the program runs, UserInformation.Value will be 0
Thank you very much for those who are replying to my question.
Change
_ageConfirmation.ShowDialog();
to
_ageConfirmation.Show();

How to use class type array in different forms in c#

I am beginner to c#. I am stuck on this assignment. I am trying to store values in class type global array but array is not saving this. I have tried a lot but failed.
Here is the code:
public class GlobalVariable
{
public static Employeeclass[] staff = new Employeeclass[10];
public static int total=0;
}
public class Employeeclass
{
public int id;
public string name;
public double salary;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var myform = new Form2();
myform.Show();
}
private void button2_Click(object sender, EventArgs e)
{
var myForm = new Form3();
myForm.Show();
}
private void button3_Click(object sender, EventArgs e)
{
double totalsalary = 0;
for (int i = 0; i < GlobalVariable.total; i++)
{
totalsalary+=GlobalVariable.staff[i].salary;
}
string a = GlobalVariable.total.ToString();
string b = totalsalary.ToString();
MessageBox.Show("total employee = " + a +"\ntotal salary = " + b);
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}
public void button1_Click(object sender, EventArgs e)
{
if (textBox2 == null)
{
MessageBox.Show("please enter employee name");
}
else
{
GlobalVariable.staff[GlobalVariable.total].id = Convert.ToInt32(textBox1.Text);
GlobalVariable.staff[GlobalVariable.total].name = textBox2.Text;
GlobalVariable.staff[GlobalVariable.total].salary = 0.0;
GlobalVariable.total++;
}
this.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = (GlobalVariable.total + 1).ToString();
}
}
public partial class Form3 : Form
{
//string temp;
//double a;
public Form3()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.Items.Clear();
for (int i = 0; i < GlobalVariable.total; i++)
{
comboBox1.Items.Insert(i,GlobalVariable.name[i]);
// comboBox1.Items.Add(GlobalVariable.name[i]);
}
if (comboBox1.SelectedItem != null)
{
textBox1.Enabled = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
var myform = new Form2();
myform.Show();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem != null)
{
textBox1.Enabled = true;
}
}
}
Your code doesn't initialize the employees. You have to create a new instance of the employee first (unlike with structs, where the default is already a fully working "instance"):
public void button1_Click(object sender, EventArgs e)
{
if (textBox2 == null)
{
MessageBox.Show("please enter employee name");
}
else
{
// Create a new instance in the array
GlobalVariable.staff[GlobalVariable.total] = new Employeeclass();
GlobalVariable.staff[GlobalVariable.total].id =
Convert.ToInt32(textBox1.Text);
GlobalVariable.staff[GlobalVariable.total].name = textBox2.Text;
GlobalVariable.staff[GlobalVariable.total].salary = 0.0;
GlobalVariable.total++;
}
this.Close();
}
However, I have to point out this is a very unhappy design. Global variables? Fixed-length arrays for variable-length data? Non-existent encapsulation?
For example, a better way might be to create the dialogs as, well, dialogs:
private NewEmployeeForm()
{
InitializeComponent();
}
public static EmployeeClass ShowDialog()
{
var frm = new NewEmployeeForm();
while (frm.ShowDialog() == DialogResult.OK)
{
if (string.IsNullOrEmpty(frm.tbxName.Text))
{
MessageBox.Show("Please, enter the employee name.");
}
else
{
var emp = new EmployeeClass();
emp.Id = int.Parse(frm.tbxId.Text);
emp.Name = frm.tbxName.Text);
return emp;
}
}
return null;
}
Forget coding like it's 1980. It's really necessary to separate your code into more or less isolated parts. Read up a bit on object oriented programming, especially encapsulation. Use meaningful names for your variables and controls, even in your learning projects! You really need the habit, it's non-negotiable.
Also, try to look for a way that solves your problem first. For example, there's a List class in .NET, that handles a self-expanding list of data. So you can use something like this:
List<EmployeeClass> employees = new List<EmployeeClass>();
employees.Add(emp1);
employees.Add(emp2);
employees.Add(emp3);
MessageBox.Show("I've got " + employees.Count + " employees!");
Don't forget error handling. I know you're just making a learning project, but again, you want the right habits. Parsing a string to an integer? Check that it's actually an integer first. Handle the possible exception. Use data validation. If I enter hi in your textBox1, your application is going to crash or show an "break / continue / abort" dialogue. That's not good.
You need to initialize each of the "EmployeeClass" Objects in your array.
By default, when the array is created it has 10 slots filled with "null"
I recommend adding a static constructor:
public static class GlobalVariable
{
public static Employeeclass[] staff;
public static int total=0;
static GlobalVariable()
{
staff = new Employeeclass[10];
for (int i = 0; i < staff.Length; i++)
staff[i] = new EmployeeClass();
}
}
The static constructor is called when you first reference anything in the GlobalVariable class. Also the class should be declared "static" because all of its members are static. The compiler can make more efficient code in this way.
Cheers and good luck learning C#
for (int i = 0; i < GlobalVariable.total; i++)
GlobalVariable.total is 0, so this loop will never be run through. Either set total to 10, or change to:
for (int i = 0; i < GlobalVariable.staff.Count; i++)
Also, there's no actual elements in the staff array, so it wouldn't work anyway.

How can I init items of a tab?

I have a form with 2 tabs on it. I can chose the tab viewed after initialization and I need some initial code every time after the tab2 is initialized:
public partial class SetupComponent : Form
{
public SetupComponent(bool tab2)
{
InitializeComponent();
if (tab2)
{
this.tabControl1.SelectedTab = tabPage2;
}
}
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.ScrollToCaret();
textBox2.SelectionStart = textBox2.Text.Length;
textBox2.Focus();
}
}
if I call this class with tab2=false and then click onto tab2, tabControl1_SelectedIndexChanged is called.
But if I select the tab2=true during SetupComponent, I find no possibility to do that code. All the TabControl1_Events I found are too early and I don`t find a matching TabPage2_Event.
How can I manage it?
I managed this problem using the Paint_Event:
bool activated = false;
private void tabPage2_Paint(object sender, PaintEventArgs e)
{
if (!activated)
{
tabControl1_SelectedIndexChanged(null, null);
activated = true;
}
}
I use the variable because the Paint_Event is called many times.

How to Create Find in Notepad in C#

I am trying to create a notepad like application in C# by using a Textbox.
I want to implement find function in it. I want an ability to search the text entered in textbox of Find form in textbox of Form1 and then highlight it.
Please help i am unable to do it
Form1.cs
private void findToolStripMenuItem_Click(object sender, EventArgs e)
{
Find f = new Find();
f.Show();
}
public void find()
{
int idx = 0;
while((idx=textBox1.Text.IndexOf(text))!=1)
{
textBox1.Select();//Select the text which are found
}
}
Find.cs
public partial class Find : Form
{
Form1 f = new Form1();
public Find()
{
InitializeComponent();
}
private void Cancelbutton2_Click(object sender, EventArgs e)
{
this.Close();
}
private void Findbutton1_Click(object sender, EventArgs e)
{
f.text =textBox1.Text;
f.find();
}
You need to specify the start and length parameter in the "Select" method. For Example:
textBox1.Select(idx, text.Length);
You can only highlight one section of data at a time with the standard TextBox. Try FastColourTextbox if you want better support.
private void textBox1_Enter(object sender, System.EventArgs e){
if (!String.IsNullOrEmpty(textBox1.Text))
{
textBox1.SelectionStart = 0;
textBox1.SelectionLength = textBox1.Text.Length;
}
}

Categories

Resources