7 Day Average Cases Form - c#

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");
}
}
}

Related

How to conbine two diffrence label's number to a new label?

I need to calculate the Lb1SumF plus Lb2SumF equal Lb3SumF.
I ran it, and somehow the label3 does not display the expected result.
Here is a screenshot from result.
Here is my code.
private void Form1_Load(object sender, EventArgs e)
{
TX1.TabIndex=0;
}
private void TX1_TextChanged(object sender, EventArgs e)
{
try
{
int sumF;
sumF = Convert.ToInt32(Lb1PriceF.Text) * Convert.ToInt32(TX1.Text);
Lb1SumF.Text = Convert.ToString(sumF); //Label1 sum
}
catch
{
Lb1SumF.Text = "0";
}
}
private void TX2_TextChanged(object sender, EventArgs e)
{
try
{
int sumF;
sumF = Convert.ToInt32(Lb2PriceF.Text) * Convert.ToInt32(TX2.Text);
Lb2SumF.Text = Convert.ToString(sumF); //Label2 sum
}
catch
{
Lb2SumF.Text = "0";
}
}
private void Lb3_TextChanged(object sender, EventArgs e)
{
int i = Convert.ToInt32(Lb1SumF.Text);
int j = Convert.ToInt32(Lb2SumF.Text);
Lb3.Text = Convert.ToString(i+j); // Label3 sum
}
Lb3_TextChanged might never be invoked as you are not changing the text of the label. I would suggest to change it to a private method and not an event handler. Here is what the code could be like:
private void TX1_TextChanged(object sender, EventArgs e)
{
try
{
int sumF;
sumF = Convert.ToInt32(Lb1PriceF.Text) * Convert.ToInt32(TX1.Text);
Lb1SumF.Text = Convert.ToString(sumF); //Label1 sum
// Call to update sum
UpdateSum();
}
catch
{
Lb1SumF.Text = "0";
}
}
private void TX2_TextChanged(object sender, EventArgs e)
{
try
{
int sumF;
sumF = Convert.ToInt32(Lb2PriceF.Text) * Convert.ToInt32(TX2.Text);
Lb2SumF.Text = Convert.ToString(sumF); //Label2 sum
// Call to update sum
UpdateSum();
}
catch
{
Lb2SumF.Text = "0";
}
}
// private void Lb3_TextChanged(object sender, EventArgs e)
private void UpdateSum()
{
int sum = 0;
if(!string.IsNullOrEmpty(Lb1SumF.Text) && !string.IsNullOrEmpty(Lb2SumF.Text))
{
sum = Convert.ToInt32(Lb1SumF.Text) + Convert.ToInt32(Lb2SumF.Text);
}
Lb3.Text = Convert.ToString(sum);
}
Replace you code with this it will work, you are using * operator where you have to use + operator, I have commented that lines in your code and replaced it for better understanding.
Happy Coding
namespace WindowsFormsApp8
{
public partial class Form1 : Form
{
private void Lb1SumF_Click(object sender, EventArgs e)
{
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
TX1.TabIndex=0;
}
private void label4_Click(object sender, EventArgs e)
{
}
private void TX1_TextChanged(object sender, EventArgs e)
{
try
{
int sumF;
//sumF = Convert.ToInt32(Lb1PriceF.Text) * Convert.ToInt32(TX1.Text); // You were doing wrong here , you were multiplying these values
sumF = Convert.ToInt32(Lb1PriceF.Text) + Convert.ToInt32(TX1.Text);
Lb1SumF.Text = Convert.ToString(sumF); //Label1 sum
}
catch
{
Lb1SumF.Text = "0";
}
}
private void TX2_TextChanged(object sender, EventArgs e)
{
try
{
int sumF;
//sumF = Convert.ToInt32(Lb2PriceF.Text) * Convert.ToInt32(TX2.Text); //you are doing it wrong here , you are multiplying
sumF = Convert.ToInt32(Lb2PriceF.Text) + Convert.ToInt32(TX2.Text);
Lb2SumF.Text = Convert.ToString(sumF); //Label2 sum
}
catch
{
Lb2SumF.Text = "0";
}
}
private void Lb3_TextChanged(object sender, EventArgs e)
{
int i = Convert.ToInt32(Lb1SumF.Text);
int j = Convert.ToInt32(Lb2SumF.Text);
Lb3.Text = Convert.ToString(i+j); // Label3 sum
}
private void Lb3SumF_Click(object sender, EventArgs e)
{
}
}
}

Running Total of Ones Count in WinForms

I'm writing a code where we need to find all the ones in a character and display them as a total. However, the code updates the total for each character pressed, rather than adding all previous ones counts.
Help would be appreciated.
namespace ica5_eventdriven
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
listBox1.Enabled = true;
lblKeyCode.Text = e.KeyChar.ToString();
listBox1.Items.Add(Convert.ToString(Convert.ToByte(e.KeyChar), 2));
List<byte> byteList = new List<byte>();
byteList.Add((byte)e.KeyChar);
byte binaryVal = Convert.ToByte(e.KeyChar);
int ones = 0;
int zeros = 0;
foreach (byte val in byteList)
{
for (int i = 0; i < 8; i++)
{
if ((binaryVal & 1) == 1)
{
ones++;
lblOnesCount.Text = ones.ToString();
}
else
zeros++;
binaryVal >>= 1;
}
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}

Application Runs Fine, But Form Design Appears Blank

I'm trying to make it so that my form does not appear blank. It was working before, It wouldn't let me save my file at one point so I renamed it to form3temp and now the form shows up when I run it, but not when I look at it in design view. Form 5 also does the same thing. The rest of my 7 forms are fine.
How it appears inside design
https://i.gyazo.com/06994988ff2f307d5042c0bafec1c43e.png
How it appears when I run the application
https://gyazo.com/97c1838e55f5f595b09211f2ee742c9f
namespace LawnCarePrototype
{
public partial class Form31 : Form
{
public static decimal yardCost = 0.0M;
decimal yardSizeMultiplier = 0.0M;
public Form31()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
yardSizeMultiplier = 0.0M;
yardCost = 0.0M;
if (radioButton1.Checked)
{
yardSizeMultiplier = 0.8M;
}
if (radioButton2.Checked)
{
yardSizeMultiplier = 1.0M;
}
if (radioButton3.Checked)
{
yardSizeMultiplier = 1.2M;
}
if (checkBox1.Checked)
{
yardCost =+ 15.00M * yardSizeMultiplier;
//2 EDGE
Global.edgeExp = 15.00M * yardSizeMultiplier;
}
if (checkBox2.Checked)
{
yardCost =+30.00M * yardSizeMultiplier;
Global.bushExp = 30.00M * yardSizeMultiplier;
//3 BUSH
}
if (checkBox3.Checked)
{
yardCost =+ 25.00M * yardSizeMultiplier;
Global.leafExp = 25.00M * yardSizeMultiplier;
//4 LEAF
}
if (checkBox4.Checked)
{
yardCost =+ 35.00M * yardSizeMultiplier;
//1 LAWN
Global.MowExp = 35.00M * yardSizeMultiplier;
}
if (yardCost == 0.00M)
{
MessageBox.Show("Please Input Your Selection");
}
else
{
Form4 form4obj = new Form4();
form4obj.Show();
this.Close();
}
Global.subTotal = yardCost;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2obj = new Form2();
form2obj.Show();
this.Close();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
}
I expect the form design to appear because I don't see any errors.
Not sure what could be causing this in my code.
Side Note: Sorry for the poor code format!

Output to textbox and improving the code

So I'm learning C# and just hit the Forms section and it's not going aswell as I hoped and Im feeling as my code isn't properly written.
Im also having problems figuring out how to output my calculated varible Im writting in with a button press.
What im asking for : Help with outputing my calculation from CalcFuelConsumptionPerKm() for example too a uneditible textbox by pressing a button
Also thanks for editing and helping out a beginner like me! You guys are awesome!
http://i.imgur.com/fcvV0yH.png > how Winform looks
Winform :
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
double obedomitor, fuel, price , oldvalue;
Fuel fc;
public Form1()
{
InitializeComponent();
fc = new Fuel();
}
private void GroupBox1_Enter(object sender, EventArgs e)
{
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
if (TextBox1.Text.Trim() != "")
{
try
{
obedomitor = Convert.ToDouble(TextBox1.Text.Trim());
fc.SetCurrentReading(obedomitor);
}
catch
{
MessageBox.Show("Please enter a valid number");
TextBox1.Text = "";
}
}
}
private void TextBox2_TextChanged(object sender, EventArgs e)
{
if (TextBox2.Text.Trim() != "")
{
try
{
oldvalue = Convert.ToDouble(TextBox1.Text.Trim());
fc.setPreviousReading(oldvalue);
}
catch
{
MessageBox.Show("Please enter a valid number");
TextBox2.Text = "";
}
}
}
private void Button1_Click(object sender, EventArgs e)
{
}
private void TextBox3_TextChanged(object sender, EventArgs e)
{
if (TextBox3.Text.Trim() != "")
{
try
{
fuel = Convert.ToDouble(TextBox3.Text.Trim());
fc.SetFuelAmount(fuel);
}
catch
{
MessageBox.Show("Please enter a valid number");
TextBox1.Text = "";
}
}
}
private void TextBox4_TextChanged(object sender, EventArgs e)
{
if (TextBox4.Text.Trim() != "")
{
try
{
price = Convert.ToDouble(TextBox4.Text.Trim());
fc.setUnitPrice(price);
}
catch
{
MessageBox.Show("Please enter a valid number");
TextBox1.Text = "";
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void TextBox5_TextChanged(object sender, EventArgs e)
{
}
private void TextBox7_TextChanged(object sender, EventArgs e)
{
}
}
}
My other class :
namespace WindowsFormsApplication1
{
class Fuel
{
double CurrentCal;
double FuelAmount;
double PreReading;
double unitPrice;
double km;
public void Fuelcalculator()
{
GetPreviousReading();
}
public double CalcConsumptionKilometerPerLiter()
{
km = CurrentCal - PreReading;
double litPerKm = FuelAmount / km;
return litPerKm;
}
public double CalcConsumptionPerMetricMile()
{
const double kmToMileFactor = 0.621371192;
double litPerKm = CalcConsumptionKilometerPerLiter();
double litPerMetricMile = litPerKm / kmToMileFactor;
return litPerMetricMile;
}
public double CalcCostPerKm()
{
double cost = (FuelAmount / km) * unitPrice;
return cost;
}
public double CalcFuelConsumptionPerKm()
{
double consumption = FuelAmount / km;
return consumption;
}
public double CalcConsumptionKilometerPerSweMil()
{
double literPerMil = CalcConsumptionKilometerPerLiter();
literPerMil = literPerMil*10;
return literPerMil;
}
public double GetCurrentReading()
{
return CurrentCal;
}
public double GetFuelAmount()
{
return FuelAmount;
}
public double GetPreviousReading()
{
double previous = CurrentCal;
return previous;
}
public double UnitPrice()
{
return unitPrice;
}
public void SetCurrentReading(double newValue)
{
CurrentCal = newValue;
}
public void SetFuelAmount(double newValue)
{
FuelAmount = newValue;
}
public void setPreviousReading(double newValue)
{
PreReading = newValue;
}
public void setUnitPrice(double newValue)
{
unitPrice = newValue;
}
}
}
If you want everything to update in realtime (which it sounds like you do) I would have a "UpdateResult" method that sets all the "output" text box's text properties:
private void UpdateResult()
{
TextBox3.Text = fc.CalcConsumptionKilometerPerLiter().ToString();
//All the others
}
And invoke that once you have validated the user's input in the "TextChanged" events. For example:
private void TextBox1_TextChanged(object sender, EventArgs e)
{
if (TextBox1.Text.Trim() != "")
{
try
{
obedomitor = Convert.ToDouble(TextBox1.Text.Trim());
fc.SetCurrentReading(obedomitor);
UpdateResults();
}
catch
{
MessageBox.Show("Please enter a valid number");
TextBox1.Text = "";
}
}
}
A couple quick notes since you are learning:
TextBoxX is not a good naming convention. Give your controls descriptive names
Since you mentioned it in a comment, double.TryParse is used for converting inputted strings into numbers. It shouldn't be involved in your output
Instead of using .Trim != "", you could just use !String.IsWhitespaceOrEmpty. It reads a lot better :)
If you expect user error, exceptions are expensive. Use double.TryParse instead of Convert.ToDouble (which really uses double.Parse) so you can have a safer, non-throwing check for user input.

Having problems removing a string from a sting list

I want to remove an item from a list...
I am obviously missing something...I have tried just about every variation including EXCEPT, REMOVE, etc...
When debugging, I step through each ling, but when it gets to btnRemove_Click, it steps through removing but does not remove anything...it acts as if I never sent a command to remove anything???
Help!
public partial class frmUpdate : Form
{
private Student student = new Student();
private string _scores;
public frmUpdate()
{
InitializeComponent();
}
public string GetUpdatedScores(Student s)
{
txtName.Text = s.Name;
_scores = s.Scores;
FillStudentGrades();
this.ShowDialog();
return _scores;
}
private void FillStudentGrades()
{
lstScores.Items.Clear();
string[] grades = splitGrades(_scores);
foreach (string s in grades)
{
lstScores.Items.Add(s.ToString());
}
}
private void lstScores_SelectedIndexChanged(object sender, EventArgs e)
{
int i = lstScores.SelectedIndex;
}
private void btnAdd_Click(object sender, EventArgs e)
{
frmAddScore addScore = new frmAddScore();
_scores += " " + addScore.AddScore();
FillStudentGrades();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
int i = lstScores.SelectedIndex;
}
private void btnRemove_Click(object sender, EventArgs e)
{
int i = lstScores.SelectedIndex;
}
private void btnRemove_Click(object sender, EventArgs e)
{
if (lstScores.SelectedIndex < 0)
{
MessageBox.Show("You Must Select A Grade.");
btnUpdate.Focus();
}
else
{
int i = lstScores.SelectedIndex;
string[] grades = splitGrades(_scores);
string message = "Are you sure you want to remove " + grades[i].ToString() + "?";
DialogResult button = MessageBox.Show(message, "Confirm Remove",
MessageBoxButtons.YesNo);
if (button == DialogResult.Yes)
{
int count = 0;
foreach (char c in grades[i])
{
if (char.IsDigit(c))
{
count++;
}
}
int a = _scores.IndexOf(grades[i].ToString());
_scores = _scores.Remove(a, (count + 1));
FillStudentGrades();
btnOk.Focus();
}
else
{
btnOk.Focus();
}
}
}
private void btnClearAll_Click(object sender, EventArgs e)
{
}
private void btnOk_Click(object sender, EventArgs e)
{
student.Name = txtName.Text;
student.Scores = _scores;
this.Close();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
public string[] splitGrades(string s)
{
string[] grades = s.Split(' ');
return grades;
}
}
In C#, strings are immutable. _scores.Remove(i); doesn't change _scores. Instead it returns a new string object that you can assign to a variable, for example, back to _scores like this:
_scores = _scores.Remove(i);
you need to use RemoveAt methos - as you are trying to remove index and not the value

Categories

Resources