I am making a program that calculates energy usage. I have created a single dimensional integer array that stores the power ratings for each of the appliances on the program. When the user clicks on a checkbox I want to get the 1st element of the array and use it in a calculation.
What code needs to go in the checkbox method?
Also, how do I convert the int values to string so I can print them in a textbox?
public Form1()
{
InitializeComponent();
int[] AppliancePower = new int[3];
AppliancePower[0] = 5000;
AppliancePower[1] = 4000;
AppliancePower[2] = 7000;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
}
What about
public class Form1
{
private int[] AppliancePower = new[]
{
5000,
4000,
7000
};
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
var value = AppliancePower[0];
DoSomeFanyCalculation(value);
this.textBox1.Text = value.ToString();
}
else
{
this.textBox1.Text = String.Empty;
}
}
}
You can do what the other 2 answer suggested, or you can save a step and just do this:
this.textBox1.Text = (checkBox1.Checked) ? AppliancePower[0].ToString() : string.Empty ;
Also, you need to declare the AppliancePower on the class level, and not in your constructor:
// class level:
int[] AppliancePower;
public Form1()
{
InitializeComponent();
AppliancePower = new int[3];
AppliancePower[0] = 5000;
AppliancePower[1] = 4000;
AppliancePower[2] = 7000;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
this.textBox1.Text = (checkBox1.Checked) ? AppliancePower[0].ToString() : string.Empty ;
}
Isn't it easy.
public class Form1
{
public int[] AppliancePower;
public Form1()
{
InitializeComponent();
AppliancePower = new int[3];
AppliancePower[0] = 5000;
AppliancePower[1] = 4000;
AppliancePower[2] = 7000;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if(AppliancePower.Length > 0)
{
int FirstValue = AppliancePower[0];
string StringValue = FirstValue .ToString();
}
}
}
Related
The array in the parent form is updated every 100 milliseconds.
Once the child form is opened with menustrip in parent form, the data is passed to child form
Issue:
Till now, I have had success in passing the array data, but I need to update it periodically in the child form also, and I have some difficulties with setting the timer in child form.
Form1: or Parent Form
string[] ArrayPack1Cells = new string[28];
//All the values are first stored in 2D array `volt_info_array[packidindex, voltage_index]`
//and after scaling it, elements store in 1D array depending on the `packidindex` value
Voltages = ((volt_info_array[packidindex, voltage_index] / 1000));
switch(PackIndexes)
{
case 1:
// if size is 28, then convert to array to be passed to child form.
if(ListPack1Cells.Count == 28)
{
ArrayPack1Cells = ListPack1Cells.ToArray();
}
break;
case 2:
.....
}
private void viewToolStripMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem menu = sender as ToolStripMenuItem;
switch (menu.Name)
{
case "pack1ToolStripMenuItem":
if (Application.OpenForms["Pack1"] is Pack1 pack1)
{
pack1.Focus();
return;
}
pack1 = new Pack1();
pack1.TakeThis(ArrayPack1Cells);
pack1.MdiParent = this;
pack1.Show();
Array.Clear(ArrayPack1Cells, 0, ArrayPack1Cells.Length);// Clear it once send to form2
break;
}
Form2: or Child/Pack1 Form
public void TakeThis(string[] ArrayPack1Cells), method copies all the 28 arrays in the texboxes but only once.
public List<Control> Cell_Volt1 = new List<Control>();
public string[] f_temp = new string[28];
public Pack1()
{
InitializeComponent();
Cell_tbxArray();
if (P1_timer.Enabled == false)
{
P1_timer.Enabled = true;
P1_timer.Tick += new System.EventHandler(this.P1_timer_Tick);
P1_timer.Start();
}
else if (P1_timer.Enabled)
{
1_timer.Stop();
P1_timer.Enabled = true;
P1_timer.Start();
}
}
private void Cell_tbxArray()
{
for (int i = 0; i < tableLayoutPanel1.Controls.Count; i++)
{
if (tableLayoutPanel1.Controls[i].GetType() == typeof(TextBox))
{
Cell_Volt1.Add(tableLayoutPanel1.Controls[i]);
}
}
}
public void TakeThis(string[] ArrayPack1Cells)
{
f_temp = ArrayPack1Cells;
int index = 0;
foreach (string item in f_temp)
{
Cell_Volt1[index].Text += item;
index++;
}
}
private void P1_timer_Tick(object sender, EventArgs e)
{
for (int i = 0; i < Cell_Volt1.Count; i++)
{
Cell_Volt1[i].Text += f_temp[i];
}
}
The private void P1_timer_Tick(object sender, EventArgs e) isnt working at all.
Here is my take.
Parent:
public static class Consts
{
public const int NPACKS = 10, NVOLTS = 28;
}
public partial class ParentForm : Form
{
double[,] data = new double[Consts.NPACKS, Consts.NVOLTS];
double[][] uidata = new double[Consts.NPACKS][];
Dictionary<int, PackForm> forms = new Dictionary<int, PackForm>();
public ParentForm()
{
InitializeComponent();
for (int i = 0; i < Consts.NPACKS; i++)
{
uidata[i] = new double[Consts.NVOLTS];
}
}
// wild guess - not clear how do you update it - all of them or slices
void DataContinuousUpdate(double value, int npack, int nvolt)
{
data[npack, nvolt] = value;
var slice = uidata[npack];
// in case a form is trying to refresh UI
lock (slice)
slice[nvolt] = value;
}
void OpenPack(int npack)
{
// assuming access to this method is serial
if (forms.ContainsKey(npack))
return;
var slice = uidata[npack];
lock (slice)
{
var form = new PackForm(npack, slice);
forms.Add(npack, form);
}
}
}
Pack:
public partial class PackForm : Form
{
public int ID { get; private set; }
public double[] Data { get; private set; }
public double ValueScale { get; set; }
TextBox[] VoltTextBox = new TextBox[Consts.NVOLTS];
Timer timer;
private PackForm()
{
InitializeComponent();
CreateTextBoxes();
ValueScale = 1000.0;
this.FormClosing += PackForm_FormClosing;
}
public PackForm(int iD, double[] data) : this()
{
InitializeComponent();
ID = iD;
Data = data;
StartTimer();
}
private void PackForm_FormClosing(object? sender, FormClosingEventArgs e)
{
StopTimer();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void StartTimer()
{
StopTimer();
timer = new Timer();
timer.Enabled = true;
timer.Interval = 1000;
timer.Tick += Timer_Tick;
}
private void StopTimer()
{
if (timer == null) return;
timer.Enabled = false;
timer.Tick -= Timer_Tick;
}
private void Timer_Tick(object? sender, EventArgs e)
{
if (Data == null) return;
lock(Data)
{
for (int i = 0; i < Data.Length; i++)
{
VoltTextBox[i].Text += Data[i];
}
}
}
}
I am a newbie and I am honestly struggling a lot with this. I am trying to calculate all the entries from the texbox to the listbox and then divide by 7 and display the average in an output label. I am having trouble displaying the case average. Here is the code:
public partial class formAverageWeeklyCases : Form
{
int SEVEN = 7;
public formAverageWeeklyCases()
{
InitializeComponent();
}
private void buttonExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void buttonEnter_Click(object sender, EventArgs e)
{
if (textBoxCaseEntry.Text.Trim().Length >= 1)
{
listBoxDailyCases.Items.Add(textBoxCaseEntry.Text.Trim());
textBoxCaseEntry.Text = string.Empty;
textBoxCaseEntry.Focus();
}
else
{
MessageBox.Show("The number entered does not appear to be valid");
textBoxCaseEntry.Text = string.Empty;
textBoxCaseEntry.Focus();
}
}
private void buttonReset_Click(object sender, EventArgs e)
{
textBoxCaseEntry.Text = string.Empty;
listBoxDailyCases.Items.Clear();
labelOutputDailyAverage.Text = string.Empty;
}
private void textBoxAverageWeeklyCases_TextChanged(object sender, EventArgs e)
{
if (listBoxDailyCases.SelectedItems.Count <= SEVEN)
{
double average = listBoxDailyCases.SelectedItems.Count / SEVEN;
labelOutputDailyAverage.Text.Show(+average);
}
else
{
MessageBox.Show("Please enter a only 7 case count numbers");
}
}
}
If I understand you correctly, you want to collect 7 numbers from the user and then calculate the average? If yes, I suggest you declare a list of ints (or doubles if you need doubles), then call TryParse to validate the user input and then calculate the average when needed:
public partial class formAverageWeeklyCases : Form
{
const int SEVEN = 7;
private List<int> numbers = new List<int>(SEVEN); // NEW
public formAverageWeeklyCases()
{
InitializeComponent();
}
private void buttonExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void buttonEnter_Click(object sender, EventArgs e)
{
if (int.TryParse(textBoxCaseEntry.Text.Trim(), out int parsed)) // NEW
{
numbers.Add(parsed); // NEW
textBoxCaseEntry.Text = string.Empty;
textBoxCaseEntry.Focus();
}
else
{
MessageBox.Show("The number entered does not appear to be valid");
textBoxCaseEntry.Text = string.Empty;
textBoxCaseEntry.Focus();
}
}
private void buttonReset_Click(object sender, EventArgs e)
{
textBoxCaseEntry.Text = string.Empty;
listBoxDailyCases.Items.Clear();
labelOutputDailyAverage.Text = string.Empty;
}
private void textBoxAverageWeeklyCases_TextChanged(object sender, EventArgs e)
{
if (listBoxDailyCases.SelectedItems.Count <= SEVEN)
{
double average = numbers.Sum() / SEVEN; // NEW
labelOutputDailyAverage.Text = average.ToString();
}
else
{
MessageBox.Show("Please enter a only 7 case count numbers");
}
}
}
namespace DivingScorer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double[] judgesScore;
private void Form1_Load(object sender, EventArgs e)
{
}
private void computeScore_Click(object sender, EventArgs e)
{
double degreeDifficulty;
int scoreBox2;
int scoreBox3;
int scoreBox4;
int scoreBox5;
scoreBox2= Convert.ToInt32(textBox2.Text);
scoreBox3 = Convert.ToInt32(textBox3.Text);
scoreBox4 = Convert.ToInt32(textBox4.Text);
scoreBox5 = Convert.ToInt32(textBox5.Text);
judgesScore[scoreBox2] = Convert.ToDouble(textBox2.Text);
judgesScore[scoreBox3] = Convert.ToDouble(textBox3.Text);
judgesScore[scoreBox4] = Convert.ToDouble(textBox4.Text);
judgesScore[scoreBox5] = Convert.ToDouble(textBox5.Text);
}
}
}
I'm not sure what you plan do with that array. Here is how you create an array with data from textboxes.
double[] judgesScore;
private void computeScore_Click(object sender, EventArgs e)
{
judgesScore = new[]
{
Convert.ToDouble(textBox2.Text),
Convert.ToDouble(textBox3.Text),
Convert.ToDouble(textBox4.Text),
Convert.ToDouble(textBox5.Text)
};
}
I personally like using Generic List, unless I'm implementing very high efficiency algorithm.
IList<double> judgesScore;
private void computeScore_Click(object sender, EventArgs e)
{
judgesScore = new List<double>
{
Convert.ToDouble(textBox2.Text),
Convert.ToDouble(textBox3.Text),
Convert.ToDouble(textBox4.Text),
Convert.ToDouble(textBox5.Text)
};
}
I want to add text from textbox to string[] array by pressing button3 i value will add to new array and clear textbox.
Button1 is to go up on array and Button2 is for go down.
I make this but it wont work:
namespace Test
{
public partial class Form1 : Form
{
public int arr1 = 0;
public int arr2 = 0;
public string[] array = new string[100];
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (arr1 < array.Length - 1)
{
if (array[arr1] != "")
{
arr1++;
textBox1.Text = array[arr1];
}
}
else
{
arr1 = 0;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (arr1 < array.Length - 1)
{
if (array[arr1] != "")
{
arr1--;
textBox1.Text = array[arr1];
}
}
else
{
arr1 = 0;
}
}
private void button3_Click(object sender, EventArgs e)
{
array[arr1] = textBox1.Text;
listBox1.Items.Add(array[arr1]);
arr2++;
textBox1.Text = "";
}
}
}
Can someone help me with this?
Thanks
replace arr2++ by arr1++ as following
private void button3_Click(object sender, EventArgs e)
{
array[arr1] = textBox1.Text;
listBox1.Items.Add(array[arr1]);
arr1++;
textBox1.Text = "";
}
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.