I want to count and sum all values in a ListBox. For example, I have the following values in my ListBox: 4, 6, 1, 7. My current value is 18. If I add a 2 with a TextBox, I need to get 20 and if I add 5 I need to get 25 in total.
If I try it with the below code, it gives me a whole other number.
Here is my code:
private void AddButton_Click(object sender, EventArgs e)
{
decimal sum;
listBox2.Items.Add(TextBox1.Text);
TextBox1.Text = "";
for (int i = 0; i < listBox2.Items.Count; i++)
{
sum += Convert.ToDecimal(listBox2.Items[i].ToString());
}
Label1.Text = sum.ToString();
}
You missed to initialize default value of sum. Assign sum = 0 before adding values to sum variable
private void AddButton_Click(object sender, EventArgs e)
{
decimal sum = 0; //Set sum = 0 by default
listBox2.Items.Add(TextBox1.Text);
TextBox1.Text = "";
for (int i = 0; i < listBox2.Items.Count; i++)
{
//To check value of sum after each iteration, you can print it on console
Console.WriteLine("Sum =" +sum);
sum += Convert.ToDecimal(listBox2.Items[i].ToString());
}
Label1.Text = sum.ToString();
}
Sorry for maybe not answer but it is strange that your compiler didn't tell you to initialize sum. The second I tested your code and it works correctly as expected that means that if the problem is not in sum variable then you made something else to this fields somewhere else so your code doesn't work correctly.
Having in mind your comment to previous person I'd say the same. In some cases (I know it's funny but) you may have viruses on your computer. Check it. Once in my life I've failed my maths lab work because of virus that interrupted my program so it drew the wrong chart !sick I know :D
private void button1_Click(object sender, EventArgs e)
{
var sum = 0;
var value = 0;
listBox1.Items.Add(textBox1.Text);
foreach (var item in listBox1.Items)
{
if (!int.TryParse(item.ToString(), out value))
continue;
sum = sum + value;
}
label1.Text = sum.ToString();
textBox1.Text = string.Empty;
}
Use of unassigned local variable 'sum', sum must be assigned before use !
decimal sum = 0;
Rest all is ok
Need to set sum to 0 and also it is probably best to use a foreach instead of a Dotloop.
private void AddButton_Click(object sender, EventArgs e) {
decimal sum = 0;
listBox2.Items.Add(TextBox1.Text);
TextBox1.Text = "";
foreach (string s in listBox2) {
sum += Convert.ToDecimal(s);
}
Label1.Text = sum.ToString();
}
Related
I am trying to make my button take input from a textbox and add it to the index. The problem is that with everything I have tried, I cannot get it to give a unique value to each position in the index.
private void addBtn_Click(object sender, EventArgs e)
{
for (int i = 0; i < nums.Length; i++)
{
if (nums[0] == 0)
{
nums[0] = int.Parse(inputText.Text);
i++;
}
if (nums[1] == 0)
{
nums[1] = int.Parse(inputText.Text);
i++;
}
}
MessageBox.Show(nums[i].ToString());
}
Right now my code inserts the value to both index positions instead of assigning a value to position 0 and then allowing the user to insert a different value into position 1 and so on and so on.
It's not clear what your intent is, but it looks like you might be trying to add numbers to an array. This code will assign the parsed string to the first item in the array that isn't zero.
private void addBtn_Click(object sender, EventArgs e)
{
int i = 0;
for (; i < nums.Length; i++)
{
if (nums[i] == 0)
{
nums[i] = int.Parse(inputText.Text);
break;
}
}
MessageBox.Show(nums[i].ToString());
}
But this would be a better way, because the user might type "0":
private int _lastUsedIndex = -1;
private void addBtn_Click(object sender, EventArgs e)
{
var number = int.Parse(inputText.Text);
// Increment by one
++_lastUsedIndex;
nums[_lastUsedIndex] = number;
MessageBox.Show(number.ToString());
}
But still, arrays aren't a great idea: They can't grow as you add things. First they're bigger than you need, then suddenly they're too small and you crash. We have better options now. Unless your teacher insists that you must use an array, use List<int> instead. In this version, we'll also use a different way to parse the number, which won't crash if the user types "LOLWUT?!?!" instead of a number:
private List<int> nums = new List<int>();
private void addBtn_Click(object sender, EventArgs e)
{
int number;
if (int.TryParse(inputText.Text, out number))
{
nums.Add(number);
MessageBox.Show(number.ToString());
}
else
{
MessageBox.Show(inputText.Text + " isn't a number, smart guy.");
}
}
I am supposed to get values entered into a text box, then display the total of the entered values, the average of the values, and the count of how many values have been entered.
So far I have coded:
List<int> intScoreList = new List<int>(20);
decimal decScoreAverage = 0m;
decimal decScoreTotal = 0m;
private void btnAdd_Click(object sender, EventArgs e)
{
int intScore = Convert.ToInt32(txtScore.Text);
int intScoreCount = 0;
intScoreList.Add(intScore);
for (int i = 0; i < intScoreList.Count; i++)
{
intScoreList[0] = intScore;
decScoreTotal += intScoreList[i];
intScoreCount++; //correct
decScoreAverage = decScoreTotal / intScoreCount; //correct
}
When I enter test values of 30 then 40, the total gives me 110 (30 + 40 * 2) rather than 70 (30 + 40). Where am I going wrong?
Use Linq. On the add button click event simply add the parsed value. Then display the Avg, and Count.
List<decimal> scoreList = new List<decimal>();
private void btnAdd_Click(object sender, EventArgs e)
{
decimalnum;
if (decimal.TryParse(txtScore.Text, out num))
{
scoreList.Add(num);
}
// Assign to count label Text property = scoreList.Count;
// Assign to average label Text property = scoreList.Average();
}
Now imagine the ability to reset all the user's input:
private void btnReset_Click(object sender, EventArgs e)
{
scoreList.Clear();
}
Utilizing the list instance you can easily add number's as entered and correctly parsed from the user. The Average Linq extension method will do all the math for you, no need to do it yourself.
To the commenters' (justified) point below, here's some more explanation.
You're total isn't computing correctly mainly because you are changing the first item of your recorded values: intScoreList[0] = intScore;. By altering it, you are interfering with the sum.
A much clean operation consists of adding your new data to the array and recomputing the sum.
List<int> intScoreList = new List<int>(20);
decimal decScoreAverage = 0m;
decimal decScoreTotal = 0m;
private void btnAdd_Click(object sender, EventArgs e)
{
int intScore = Convert.ToInt32(txtScore.Text);
int intScoreCount = 0;
intScoreList.Add(intScore);
decScoreTotal = 0;
foreach(int i in intScoreList) {
decScoreTotal += i;
}
decScoreAverage = decScoreTotal / intScoreList.Count;
intScoreCount = inScoreList.Count;
}
Note that this isn't necessarily the most efficient implementation since as the number of values increase, the foreach loop will get more and more expensive. A better approach is to keep track of the current total and average and adjust them with the new value (which you can still add to the list for other purposes if you need).
The average is computed this way:
New_average = old_average * (count-1)/count + new_value /count
And here's the new code:
List<int> intScoreList = new List<int>(20);
decimal decScoreAverage = 0m;
decimal decScoreTotal = 0m;
private void btnAdd_Click(object sender, EventArgs e)
{
int intScore = Convert.ToInt32(txtScore.Text);
int intScoreCount = 0;
intScoreList.Add(intScore);
intScoreCount = inScoreList.Count;
decScoreTotal += intScore;
decScoreAverage = decScoreAverage * (intScoreCount- 1)/intScoreCount + intScore/intScoreCount;
}
Since the loop adds up all the items,
dont' you want
decScoreTotal = 0
before your for loop?
Don't think i could be any newer to coding, so please forgive me for whats about to be asked.
Im currently writing a program that lets the user enter a desired amount of random numbers to be generated by Random via textBox (lets say 15 --> you get 15 random numbers), ranging from 1 to 1000.
When hitting the Button A, those randomized Numbers will be saved in Zahlenarray[](-->with the length of the number entered in the textbox) and displayed in label1.Text.
Then there's a Button B, that, when clicked, should sort the Numbers from Zahlenarray[] via bubblesort and display them in label2.
My problem is now that the second Method (Button B_Click) doesnt have the contents of Zahlenarray from the Button A_Click Method.
Id like to pass this data by ref via the arguments, but fiddling with public void (Object sender, EventArgs e) seems to get me in major trouble.
Can i add arguments after EventArgs e, ... or am i missing another way of getting data out f this "scope" (hope thats the right word)?
Both Methods are in the same class.
part of the code of Button A:
public void Button_Anzeigen_Click(Object sender, EventArgs e)
{
label1.Text = "";
int[] Zahlenarray = new int[Int32.Parse(textBox1.Text)];
Everything from Button B:
private void Button_Sortieren_Click(object sender, EventArgs e)
{
label2.Text = "";
label3.Text = "";
int Speicher;
for (int n = Zahlenarray.Length; n > 0; n--)
{
for (int i = 0; i < n-1; i++)
{
if (Zahlenarray[i] > Zahlenarray[i + 1])
{
Speicher = Zahlenarray[i];
Zahlenarray[i] = Zahlenarray[i + 1];
Zahlenarray[i + 1] = Speicher;
Speicher = 0;
}
}
}
foreach (int i in Zahlenarray)
{
label2.Text += i + " ";
if ((i % 9 == 0) && !(i == 0))
label2.Text += "\n";
}
}
Put your array declaration outside of your buttona click handler so you can reference it inside your button b handler.
int[] Zahlenarray;
public void Button_Anzeigen_Click(Object sender, EventArgs e)
{
label1.Text = "";
Zahlenarray = new int[Int32.Parse(textBox1.Text)];
...
}
I'm making a calculator in GUI, and I need some help.
When I enter some data in a text box, I need to store it in an array. This is how I thought of it.
int numOfPackages;//used to get user input
private void button3_Click(object sender, EventArgs e)
{
int[] weight = new int[numOfPackages];
for(int i = 0; i < numOfPackages; i++)
{
weight[i] = Convert.ToInt32(weightBox.Text);
}
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
}
And when I try to display the elements, it gives me the indexOutOfRange exception.
So, how do I display the elements of that array?
Thanks in advance.
This line
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
should be
foreach (int w in weight)
totalCostLabel.Text = "" + w;
Your current code iterates the array of weights, and tries to use the weight as an index into the array of weights, causing an index out of range exception.
Another problem is with the first loop: you are setting all values of weight to the same number:
weight[i] = Convert.ToInt32(weightBox.Text); // That's the same for all i-s
If weights are to be different, they should come from different weight boxes, or the string from a single weightBox should be processed in such a way as to produce multiple numbers (for example, by using string.Split).
You have multiple problems here. First is this:
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
This is iterating the weight array and using each value in that array. You then use that value as an index. Take the following example:
weight[0] = 0
weight[1] = 1
weight[2] = 15
In your code, the first two entries will work because there is an index of 0 and an index of 1. But when it gets to the last entry, it looks for an index of 15. You can fix this two ways, the first is to use a regular for loop:
for(int i=0; i < weight.Length; i++)
{
totalCostLabel.Text += weight[i];
}
This brings the second mistake. You aren't appending anything to your totalCostLabel in your code, you are just replacing the value. This will append all the values of weight together as one.
Another way to do this is to use the foreach loop:
foreach(int i in weight)
{
totalCostLabel.Text += i;
}
This is the same as above but you don't have to worry about indexing.
Bottom line, even after you fix your loop, you will probably need to fix the way that the label takes the text otherwise you won't get your desired result.
Maybe you wanted something more like?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
btnAdd.Enabled = false;
}
int[] weight;
int entriesMade;
int numOfPackages;
private void btnReset_Click(object sender, EventArgs e)
{
if (int.TryParse(numEntriesBox.Text, out numOfPackages))
{
weight = new int[numOfPackages];
entriesMade = 0;
btnReset.Enabled = false;
btnAdd.Enabled = true;
totalCostLabel.Text = "";
}
else
{
MessageBox.Show("Invalid Number of Entries");
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
int value;
if (int.TryParse(weightBox.Text, out value))
{
weight[entriesMade] = value;
weightBox.Clear();
totalCostLabel.Text = "";
int total = 0;
for (int i = 0; i <= entriesMade; i++)
{
total = total + weight[i];
if (i == 0)
{
totalCostLabel.Text = weight[i].ToString();
}
else
{
totalCostLabel.Text += " + " + weight[i].ToString();
}
}
totalCostLabel.Text += " = " + total.ToString();
entriesMade++;
if (entriesMade == numOfPackages)
{
btnAdd.Enabled = false;
btnReset.Enabled = true;
MessageBox.Show("Done!");
}
}
else
{
MessageBox.Show("Invalid Weight");
}
}
}
I have a simple dataGridView with 4 columns. I want to sum up values from a third column and save the result into variable on button press. I tried like this, but I always get an error saying
"Specified cast is not valid - when casting from a number, the value must be less than infinity".
P.S. Each cell is bassically a DataGridViewTextBoxColumn, meaning I can input values directly.
Code:
private void button2_Click(object sender, EventArgs e)
{
Double result = 0;
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
result += (Double)row.Cells[2].Value;
}
this.label13.Text = result .ToString();
}
What am I missing?
Rather than casting, try
result += Convert.ToDouble(row.Cells[2].Value);
With error checking
if (row.Cells[2].Value != null)
{
try
{
result += Convert.ToDouble(row.Cells[2].Value);
}
catch { }
}
DataTable dt =DataGridView1.DataSource as DataTable;
decimal total;
total=(int)dt.Compute("sum(column_name)","");
private getColSum()
{
int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
}
return sum;
}