c# values don't work correctly - c#

I'm new to c# and I tried making a simple program. After I click the button, the values won't update with their actual value, so I have to click twice to make them actually work. Here's my code:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private static int p;
private static int money;
public Form1()
{
InitializeComponent();
p = 0;
money = 100;
}
private void button1_Click(object sender, EventArgs e)
{
m.Text = money.ToString();
ex.Text = p.ToString();
if (checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("You cannot select both.", "Nope");
}
else if (checkBox1.Checked)
{
p += 2;
}
else if (checkBox2.Checked)
{
money -= 50;
p += 10;
}
else
{
return;
}
}
}
}

You need to update the text after updating the value
if (checkBox1.Checked & checkBox2.Checked)
{
MessageBox.Show("You cannot select both.", "Nope");
}
....
m.Text = money.ToString();
ex.Text = p.ToString();

Related

c# in timer tick want to count++ 0 to 30 and then count -- 30 to 0 again and again. how to do?

namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int A = 0;
private void timer1_Tick(object sender, EventArgs e)
{
A++;
if (A == 30)
{
A--;
}
textBox1.Text = A.ToString();
}
}
}
Just store the direction you're going and flip it when you reach the limits:
int A = 0;
int direction = 1;
private void timer1_Tick(object sender, EventArgs e)
{
A += direction;
if (A == 30 || A == 0)
{
direction = -direction;
}
textBox1.Text = A.ToString();
}

String unreadable when passing from one form to another in C#

I am trying to pass a string from Form2.cs to Form1.cs and then display it in a message box. For some reason, the variable in the string is not showing but the rest of the text is.
Form1.cs
Form2 otherForm = new Form2();
public void getOtherTextBox()
{
otherForm.TextBox1.Text = player1;
}
private void labelClick(object sender, EventArgs e)
{
Label clickedLabel = (Label)sender;
if (clickedLabel.BackColor != Color.Transparent)
{
return;
}
clickedLabel.BackColor = isBlackTurn ? Color.Black : Color.White;
isBlackTurn = !isBlackTurn;
Color? winner = WinCheck.CheckWinner(board);
if (winner == Color.Black)
{
MessageBox.Show( player1 + " is the winner!");
}
else if (winner == Color.White)
{
MessageBox.Show("White is the winner!");
}
else
{
return;
}
Form2.cs
public TextBox TextBox1
{
get
{
return textBox1;
}
}
this might work .. u need to call the function somewhere to make it work.
I fixed it by calling it in the label click;
so u need to click the label to update the value in the other form.
u can add this function to events like a timer event which ensures that it's always updated within a perfect time.
public void getOtherTextBox()
{
otherForm.TextBox1.Text = player1;
}
private void labelClick(object sender, EventArgs e)
{
Label clickedLabel = (Label)sender;
getOtherTextBox();
if (clickedLabel.BackColor != Color.Transparent)
{
return;
}
clickedLabel.BackColor = isBlackTurn ? Color.Black : Color.White;
isBlackTurn = !isBlackTurn;
Color? winner = WinCheck.CheckWinner(board);
if (winner == Color.Black)
{
MessageBox.Show( player1 + " is the winner!");
}
else if (winner == Color.White)
{
MessageBox.Show("White is the winner!");
}
else
{
return;
}
}
You can create a property in Form1 to hold the player name, and then in Form2, when the input of player name changed, you will update the property of Form1. See the code:
public class Form1()
{
//Code
private string PlayerName { get; set; }
private void labelClick(object sender, EventArgs e)
{
Label clickedLabel = (Label)sender;
if (clickedLabel.BackColor != Color.Transparent)
return;
clickedLabel.BackColor = isBlackTurn ? Color.Black : Color.White;
isBlackTurn = !isBlackTurn;
Color? winner = WinCheck.CheckWinner(board);
if (winner == Color.Black)
MessageBox.Show(this._playerName + " is the winner!");
else if (winner == Color.White)
MessageBox.Show("White is the winner!");
}
//More code
}
public class Form2()
{
private Form1 _frm;
public Form2()
{
this._frm = new Form1();
}
public void ShowFormWinner()
{
_frm.PlayerName = textBox1.Text;
_frm.Show();
}
public void OnPlayerNameChanged(object sender, EventArgs e)
{
_frm.PlayerName = textBox1.Text;
_frm.Show();
}
}

c# - Cannot convert from void to list

So, I got kind of stuck over my head while I tried to program something new.
I'm trying to add objectBeer_pluche or objectBeer_Elektro to my OBJberenlijst on the Beren Main form from the details Form, so I can add both instances of 2 classes to the same list.
I'm not even sure this is possible by the way. So, I would like feedback if what I am trying to do is possible to start with. I already figured VOID is not right but I am really clueless here.
This is my main beren.cs form with an OBJberenlist, that's where I try to add objectBeer_pluche or objectBeer_Elektro into it:
public partial class Beren : Form
{
public interface Berenlijst { }
public List<Berenlijst> OBJberenLijst = new List<Berenlijst>();
public Beren()
{
InitializeComponent();
}
private void Beren_Load(object sender, EventArgs e)
{
}
private void BTNToevoegen_Click(object sender, EventArgs e)
{
this.Hide();
Details Details = new Details();
if (Details.ShowDialog(this) == DialogResult.OK)
{
OBJberenLijst.Add(Details.getdetails());
}
Details.Close();
Details.Dispose();
}
public void LijstLaden()
{
foreach(Beer berenobject in OBJberenLijst)
{
LST_beren.Items.Add(berenobject.Naam);
}
}
}
}
from this form called details.cs
public partial class Details : Form
{
public Details()
{
InitializeComponent();
BTN_toevoegen.DialogResult = DialogResult.OK;
BTN_cancel.DialogResult = DialogResult.Cancel;
}
private void Details_Load(object sender, EventArgs e)
{
RDB_pluche.Checked = true;
BTN_ok.Enabled = false;
}
private void RDB_pluche_CheckedChanged(object sender, EventArgs e)
{
PANEL_pluche.Visible = true;
PANEL_elektro.Visible = false;
}
private void RDB_elektro_CheckedChanged(object sender, EventArgs e)
{
PANEL_pluche.Visible = false;
PANEL_elektro.Visible = true;
}
private void BTN_toevoegen_Click(object sender, EventArgs e)
{
open_foto.Filter = "jpg (*.jpg)|*.jpg|bmp(*.bmp)|*.bmp|png(*.png)|*.png";
if (open_foto.ShowDialog() == System.Windows.Forms.DialogResult.OK && open_foto.FileName.Length > 0)
{
TXT_adres.Text = open_foto.FileName;
PIC_beer.Image = Image.FromFile(open_foto.FileName);
}
}
private void BTN_ok_Click(object sender, EventArgs e)
{
}
public void getdetails()
{
if (RDB_pluche.Enabled == true)
{
Pluche_Beer objectBeer_pluche = new Pluche_Beer(TXTNaam_pluche.Text, open_foto.FileName, "(Wasprogramma: " + TXT_wasprogramma.ToString() + " Graden Celsius");
}
else
{
Elektronische_Beer objectBeer_Elektro = new Elektronische_Beer(TXTNaam_elekro.Text, open_foto.FileName, "aantal Batterijen: " + CMBOBatterijen.ToString());
}
}
private void Details_MouseMove(object sender, MouseEventArgs e)
{
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
TextBox textBox = c as TextBox;
if (textBox.Text != string.Empty)
{
BTN_ok.Enabled = true;
}
}
}
}
}
}
The problem is between this line...
OBJberenLijst.Add(Details.getdetails());
...and this line.
public void getdetails()
List.Add() requires an object to add, but getdetails() returns void. You probably want to change getdetails() to something like the following:
public Berenlijst getdetails()
{
if (RDB_pluche.Enabled == true)
{
return new Pluche_Beer(TXTNaam_pluche.Text, open_foto.FileName, "(Wasprogramma: " + TXT_wasprogramma.ToString() + " Graden Celsius");
}
return new Elektronische_Beer(TXTNaam_elekro.Text, open_foto.FileName, "aantal Batterijen: " + CMBOBatterijen.ToString());
}
Hopefully Pluche_Beer and Elektronisch_Beer inherent from Berenlijst. Otherwise you'll have to revise your logic in a broader way.

How to solve memory leak in window form

My problem is that memory is increased 5MB flicker form each time a call per second .
I made window flicker effect window form
[flicker form]
public partial class WarningBoxControls : Form
{
bool _isShadow;
public WarningBoxControls(WarningBoxType _Type)
{
InitializeComponent();
this.FormClosing += WarningBox_FormClosing;
this.VisibleChanged +=WarningBoxControls_VisibleChanged;
if (_Type == WarningBoxType.WarningBox_Speed)
{
MessageTitle.Text = "속력 경고";
MessageContent.Text = "자동차 속도를 줄여주세요!";
this.BackColor = Color.SkyBlue;
pictureBox1.Image = Properties.Resources.warning_speed;
}
else
{
MessageTitle.Text = "Logger 오류";
MessageContent.Text = "Logger가 활성화되지 않았습니다!";
this.BackColor = Color.MediumVioletRed;
pictureBox1.Image = Properties.Resources.warning_error;
}
}
private void WarningBoxControls_VisibleChanged(object sender, EventArgs e)
{
this.Opacity = 0.01;
if(this.Visible == true)
{
timer1.Start();
}
else
{
timer1.Stop();
}
}
private void WarningBox_FormClosing(object sender, FormClosingEventArgs e)
{
if (pictureBox1.Image != null)
{
pictureBox1.Image = null;
pictureBox1.Dispose();
}
if (timer1.Enabled == true)
{
timer1.Stop();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (_isShadow == false)
{
if (this.Opacity <= 1.0)
{
this.Opacity += 0.8;
if (this.Opacity >= 1.0)
{
_isShadow = true;
}
}
}
else
{
if (this.Opacity >= 0.01)
{
this.Opacity -= 0.08;
if (this.Opacity <= 0.01)
{
_isShadow = false;
}
}
}
}
}
And I created the class to load flicker effect form.
[load ficker form]
public class WarningBox
{
WarningBoxControls _control;
Form owner;
public WarningBox(IWin32Window _owner, WarningBoxType _Type)
{
if (_owner != null)
{
owner = (Form)_owner;
_control = new WarningBoxControls(_Type);
_control.StartPosition = FormStartPosition.Manual;
_control.Padding = new Padding(0, 0, 0, 0);
_control.ControlBox = false;
_control.ShowInTaskbar = false;
_control.Size = new Size(owner.Size.Width - 40, _control.Height - 20);
}
}
public void Show()
{
_control.Location = new Point(owner.Location.X + 20, owner.Location.Y + ((owner.Height - _control.Height) / 2));
//_control.ShowDialog();
//_control.BringToFront();
if(_control.Visible != true)
{
_control.Show();
_control.BringToFront();
}
}
public void Hide()
{
if(_control.Visible != false)
{
//_control.Visible = false;
_control.Hide();
}
}
~WarningBox()
{
if(_control != null)
{
_control.Dispose();
_control = null;
}
}
}
[Call a second method]
private void timer1_Tick(object sender, EventArgs e)
{
if (NetworkInterface.GetIsNetworkAvailable())
{
ReadLoggerStatus();
}
private void ReadLoggerStatus()
{
if (_Lights != null)
{
if (_Lights.ERR == 0) // 에러 없을때
{
pb_error.Image = Properties.Resources.none;
_WarningBox.Hide();
btn_stop.Enabled = true;
btn_start.Enabled = false;
}
else
{
pb_error.Image = Properties.Resources.error;
_WarningBox.Show();
btn_stop.Enabled = false;
btn_start.Enabled = true;
}
}
}
And Check the one error per second , call the Show() and Hide() of WarningBox. however here(ReadLoggerStatus()) is some of a problem.
my problem is that the memory each time it is called once per second increased by 5MB.
I want to know it is solve the best way.
please let me know excellent answer.
In advance, I would greetings of thanks.
Have a good day!

Can't figure what's wrong with my code

First, sorry for my English, it's not my first language.
I'm on the first grade of high school, and at my college we have a certificate program of three years in system analysis and development, along with the normal classes.
We are just starting learning c# at the course, but since we have some free time at the lab we started "playing" with winforms. I prefer to look at the code or google the error instead of asking, but this time i really can't figure what's wrong.
When i was using only one form, to get the input and show all users' information in real time (without a combobox, just labels), it all worked fine. What I want to do is, take input of five users, and , if the fields are filled correctly, add the first name of the user as an item to the combobox, and he can see the name/sex/age of previous users browsing the combobox items.
The Form1's code:
public partial class Form1 : Form
{
Form2 frm2 = new Form2();
public Form1()
{
InitializeComponent();
}
private void label9_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
variaveis.i++;
variaveis.nome[variaveis.i] = textBox1.Text;
variaveis.sobrenome[variaveis.i] = textBox2.Text;
variaveis.sexo[variaveis.i] = comboBox1.Text;
if (textBox3.Text != null)
variaveis.idade[variaveis.i] = textBox3.Text;
double num;
bool isnum = double.TryParse(variaveis.idade[variaveis.i], out num);
Form2 frm2 = new Form2();
frm2.Update();
if (variaveis.nome[variaveis.i]!=null && variaveis.sobrenome!=null && variaveis.idade[variaveis.i] != null && isnum)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.Refresh();
frm2.comboBox1.Items.Add(variaveis.nome[variaveis.i]); //Only works with the first input
if (variaveis.i == 1)
{
frm2.Show();
frm2.Location = new Point(this.Left + this.Width, this.Top);
frm2.Height = this.Height;
frm2.label6.Text = variaveis.nome[variaveis.i];
frm2.label7.Text = variaveis.sobrenome[variaveis.i];
frm2.label8.Text = variaveis.sexo[variaveis.i];
frm2.label9.Text = variaveis.idade[variaveis.i];
}
}
else
{
variaveis.i--;
MessageBox.Show("Preencha todos os campos",
"Erro");
}
if (variaveis.i >= 5)
{
button1.Enabled = false;
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.Refresh();
}
}
The Form2's code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label6.Text = variaveis.nome[comboBox1.SelectedIndex + 1]; // i don't even know if i can use an array like this
label7.Text = variaveis.sobrenome[comboBox1.SelectedIndex + 1];
label8.Text =variaveis.sexo[comboBox1.SelectedIndex + 1];
label9.Text = variaveis.idade[comboBox1.SelectedIndex + 1];
}
The variables class (I thought would be easier to work this way if I'm using multiple forms, if I'm wrong, correct me):
class variaveis
{
public static string[] nome = new string[5]; //name
public static string[] sobrenome = new string[5]; //last name
public static string[] sexo = new string[5]; //gender
public static string[] idade = new string[5]; //age(string, checked with tryparse)
public static int i = 0;
}
Sorry if it's a noob question or if the error is obvious, but I started working with WinForms a couple weeks ago.
EDIT:
So the problems now are:
-Sometimes the program throw me the error even when all conditions are apparently fulfilled.
-Can't add items to a combobox in another form. Tried this:
public void AddItem(object item)
{
comboBox1.Items.Add(variaveis.nome[variaveis.i]);
}
Calling it in Form1:
frm2.AddItem(variaveis.nome[variaveis.i]);
The syntax seems correct, but nothing happens.
If you set it up like this, i think it is easier to address your data.
public class Person
{
public string Nome {get; set;}
public string Sobrenome {get; set;}
public string Sexo {get; set;}
public string Idade {get; set;}
}
public class Variaveis
{
public Person[] People {get; set;}
public Variaveis
{
People = new Person[5];
}
}
Now you can access the data like so:
var myName = Variaveis.People[2].Nome;
I edited some things and solved the "if" problem . The new code:
public partial class Form1 : Form
{
public string[] nome = new string[5];
public string[] sobrenome = new string[5];
public string[] sexo = new string[5];
public string[] idade = new string[5];
public int i = 1;
public Form1()
{
InitializeComponent();
}
private void label9_Click(object sender, EventArgs e)
{
}
public void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(this);
nome[i] = textBox1.Text;
sobrenome[i] = textBox2.Text;
sexo[i] = comboBox1.Text;
idade[i] = textBox3.Text;
double num;
bool isnum = double.TryParse(idade[i], out num);
if (textBox1.Text !=null && textBox2.Text!=null && textBox3 != null && isnum == true)
{
frm2.comboBox1.Items.Add(textBox1.Text);
frm2.comboBox1.Update();
comboBox1.Update();
textBox4.Text = Convert.ToString(i); // just to check the variable's value, since they dont appear in the debugger tool
if (i == 1)
{
frm2.Show();
frm2.Location = new Point(this.Left + this.Width, this.Top);
frm2.Height = this.Height;
}
frm2.label6.Text = nome[i];
frm2.label7.Text = sobrenome[i];
frm2.label8.Text = sexo[i];
frm2.label9.Text = idade[i];
frm2.comboBox1.SelectedIndex = frm2.comboBox1.SelectedIndex + 1;
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
++i;
}
if(isnum == false && textBox1.Text == null && textBox2.Text == null && textBox3 == null)
{
MessageBox.Show("Preencha todos os campos", "Erro");
}
if (i >= 5)
{
button1.Enabled = false;
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.Refresh();
}
private void Form1_Load(object sender, EventArgs e)
{
}
I've noticed that all controls(not just combobox1) only respond to the first command coming from another form. If i put a textbox in form2 and call:
frm2.textBox1.Text = i;
it's going to show "1" forever. How do i solve this?
Solved the problem by myself, by adding this:
public partial class Form2 : Form
{
Form1 f1;
public Form2(Form1 f1)
{
InitializeComponent();
this.f1 = f1;
This:
public partial class Form1 : Form
{
private Form2 frm2;
and this:
public Form1()
{
InitializeComponent();
frm2 = new Form2(this);
}
The complete code with some improvements:
Form1:
public partial class Form1 : Form
{
private Form2 frm2;
public string[] nome = new string[6];
public string[] sobrenome = new string[6];
public string[] sexo = new string[6];
public string[] idade = new string[6];
public int i = 0;
public Form1()
{
InitializeComponent();
frm2 = new Form2(this);
}
public void button1_Click(object sender, EventArgs e)
{
++i;
nome[i] = textBox1.Text;
sobrenome[i] = textBox2.Text;
sexo[i] = comboBox1.Text;
idade[i] = textBox3.Text;
double num;
bool isnum = double.TryParse(idade[i], out num);
if (textBox1.Text !=null && textBox2.Text!=null && textBox3 != null && isnum == true)
{
frm2.comboBox1.Items.Add(textBox1.Text);
frm2.comboBox1.Update();
comboBox1.Update();
if (i == 1)
{
frm2.Show();
frm2.Location = new Point(this.Left + this.Width, this.Top);
frm2.Height = this.Height;
}
frm2.label6.Text = nome[i] + " " + sobrenome[i];
frm2.label8.Text = sexo[i];
frm2.label9.Text = idade[i];
frm2.comboBox1.SelectedIndex = frm2.comboBox1.SelectedIndex + 1;
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}
if(isnum == false && textBox1.Text == null && textBox2.Text == null && textBox3 == null)
{
MessageBox.Show("Preencha todos os campos", "Erro");
--i;
}
if (i >= 5)
{
button1.Enabled = false;
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.Refresh();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
Form2:
public partial class Form2 : Form
{
Form1 f1;
public Form2(Form1 f1)
{
InitializeComponent();
this.f1 = f1;
comboBox1.Items.Add("Usuários");
}
private void Form2_Load(object sender, EventArgs e)
{
}
public void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != 0)
{
label6.Text = f1.nome[comboBox1.SelectedIndex] + " " + f1.sobrenome[comboBox1.SelectedIndex];
label8.Text = f1.sexo[comboBox1.SelectedIndex];
label9.Text = f1.idade[comboBox1.SelectedIndex];
}
else
{
label6.Text = " ";
label8.Text = " ";
label9.Text = " ";
}
}
}
Thanks for the help anyway.

Categories