computing sum of numeric column in c# .net [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to calculate sum of a DataTable's Column in LINQ (to Dataset)?
In my Data_Grid_View, I have one numeric column named Amount and I want to display total of this column in one text box ,can anyone tell what will be the code for it in c# .net

Here's how you would do it with LINQ, assuming your amounts were double:
dataGridView.Rows.OfType<DataGridViewRow>()
.Sum(row => Convert.ToDouble(row.Cells["Amount"].Value));
Here's how it would actually fit into your program:
private void button2_Click(object sender, EventArgs e)
{
decimal sum = dataGridView1.Rows.OfType<DataGridViewRow>()
.Sum(row => Convert.ToDecimal(row.Cells["Money"].Value));
textBox1.Text = sum.ToString();
}

Try this :
int sum = 0;
int ColumnIndex=1; //your column index
//Iterate through all the cells of Specified ColumnIndex in each row and get the sum
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
sum += int.Parse(dataGridView1.Rows[i].Cells[ColumnIndex].Value.ToString());
}
//display sum
textBox1.Text = sum.ToString();

Related

C# sum problems

I am using the below code to get the sum of a column in a data grid view.
private void button16_Click(object sender, EventArgs e)
{
int sum = 0;
for (int i = 0; i < dataGridView4.Rows.Count; ++i)
{
sum += Convert.ToInt32(dataGridView4.Rows[i].Cells[10].Value);
}
try
{
decimal tot = 0;
for (int i=0; i <= dataGridView4.RowCount -1; i++)
{
tot += Convert.ToDecimal (dataGridView4.Rows[i].Cells[10].Value);
}
if (tot==0) {}
textBox34.Text = tot.ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I am getting the error message
Input string was not in a correct format.
ِI found that the problem is in the formatting. Becasue the SQL server data type for that column is money. and the SQL server changes any number I save to this format. 00.0000
For example, If I save 10 SQL server saves it as 10.0000
If I remove the (.) I get no errors.
If I try to sum 10.0000 + 3.0000 it never works out.
Any ideas?
Your problem is that you're trying to convert a value with a decimal point from string to int. When using the money datatype in your DB, the best datatype to use in your code will be the decimal type. See the answer on What is the best data type to use for money in C#
So doing:
int val = Convert.ToInt32("10.00");
Will yield the following error (which is what you're receiving):
Unhandled Exception: System.FormatException: Input string was not in a
correct format.
You can convert the value using the Convert.ToDecimal() method:
decimal val = Convert.ToDecimal("10.00");
If you want to remove the decimal portion of the value, you can use one of the following methods based on your requirements:
Math.Floor
Math.Ceiling
Math.Round
Math.Truncate
For example:
decimal val2 = Math.Round(val);
Or:
decimal val2 = Math.Truncate(val);
If you simply want to return the value as a string but without the decimal portion, you can do as follows:
decimal val = Convert.ToDecimal("10.00");
Console.WriteLine(val.ToString("0.#"));
Edit:
So in your code, change:
int sum = 0;
for (int i = 0; i < dataGridView4.Rows.Count; ++i)
{
sum += Convert.ToInt32(dataGridView4.Rows[i].Cells[10].Value);
}
For:
decimal sum = 0;
for (int i = 0; i < dataGridView4.Rows.Count; ++i)
{
sum += Convert.ToDecimal(dataGridView4.Rows[i].Cells[10].Value);
}

Working with arrays, think I'm not using for loop correctly

I've only been working with Arrays for a short while, and Im finding them much harder than working with Lists. For an assignment I have written a form with takes an input from a textbox and outputs a count,average, and total. The code is as follows:
int [] intScoreTotalArray = new int[20];
decimal decScoreAverage = 0m;
decimal decScoreTotal = 0m;
decimal decScoreCount = 0m;
private void btnAdd_Click(object sender, EventArgs e)
{
intScoreTotalArray[0] = Convert.ToInt32(txtScore.Text);
for(int i = 0; i < intScoreTotalArray.Length; i++)
{
decScoreTotal += intScoreTotalArray[i];
}
decScoreCount++;
decScoreAverage = decScoreTotal / decScoreCount;
But I also need to display it in a message box in a stong, and it only gives me the last value. My theory is that the problem lies in both boxes of code, or in the intial for loop.
private void btnDisplayScores_Click(object sender, EventArgs e)
{
decimal decScore = Convert.ToDecimal(txtScore.Text);
string strScoreTotal = " ";
for (int i = 0; i < intScoreTotalArray[i]; i++)
{
strScoreTotal += decScore.ToString() + "\n";
}
Array.Sort(intScoreTotalArray);
MessageBox.Show(strScoreTotal + "\n","Score Array");
Advice?
Why are you using an array to determine the count, average and total of a list of numbers? They aren't the best structure for a dynamic list of items as you have to declare an array's size when you initialize it. You SHOULD be using a list for this task.
As to why your code isn't behaving:
intScoreTotalArray[0] = Convert.ToInt32(txtScore.Text);
You are only assigning the first item in the array here.
It looks like you are using decScoreCount to keep track of the number of items in your array. I think you want to do this:
intScoreTotalArray[(int) decScoreCount] = Convert.ToInt32(txtScore.Text);

How to Add the column values in the TextChanged event?

I have type the value in GridView column.
After enter some data into the GridView, I want it to calculate the sum of one particular column.
How can I achieve this?
If what you need is to display the sum of a particular column in a dataGridView, then this could help:
private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 5)
textBox9.Text = CellSum().ToString();
}
private double CellSum()
{
double sum = 0;
for (int i = 0; i < dataGridView2.Rows.Count; ++i)
{
double d = 0;
Double.TryParse(dataGridView2.Rows[i].Cells[5].Value.ToString(), out d);
sum += d;
}
return sum;
}
Some considerations to take:
Make sure the data you are summing is in numeric form. Therefore the column type needs to be an integer, double or float (but surely not an nvarchar or varchar). This will ensure that the program does not go into error state when summing the values.
In the code above, taken from another answer in StackOverflow, the values in that column were parsed to double, to allow decimal numbers, and not simply whole numbers.
The sum needs to be stored in a variable of type double. It is up to you then what to do with it: Whether you want to store it in another place in the database or show it to the user in a label.
you have to sum the Values at your TextchangedEvent ,so please try this
protected void txtintroId_TextChanged(object sender, EventArgs e)
{
float total= 0;
foreach (GridViewRow gridViewRow in gridView.Rows)
{
lbltotal = (Label)gridViewRow.FindControl("lbltotal");
float rowValue = 0;
if (float.TryParse(lbltotal.Text.Trim(), out rowValue))
total += rowValue;
}
GridView1.FooterRow.Cells[3].Text = total.ToString();
}

Datagridview Error:: Index was out of range. How I can Solve it?

I have this form application project. I upload a snap of the sales field. Two datagridview are there. Bottom datagirdview contain TAX details. Contain of bottom datagrid came from database except “Amount” column. Amount column value provided by user or auto calculated. I write a code. When I try to execute it shows a error. Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index. How Can I solve it??
Snap::
Here is the code:
private void dgvSalesFooterAdd_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
decimal Total = 0;
decimal a=Convert.ToDecimal(lblTotalAdd.Text);
for (int i = 0; i <dgvSalesFooterAdd.Rows.Count ; i++)
{
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
}
lblFinalTotalAdd.Text = Total.ToString();
}
[NOTE: Error on
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
this two lins.]
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a *(Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
it will throw an exception because you are reading the value of 4th column which is null, because cell_value changed worked once you leave the cell...
got throught this link it will give you a better picture..
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx
and try you code like this..
void dgvSalesFooterAdd_CurrentCellDirtyStateChanged(object sender,
EventArgs e)
{
if (dgvSalesFooterAdd.IsCurrentCellDirty)
{
dgvSalesFooterAdd.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dgvSalesFooterAdd_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
decimal Total = 0;
decimal a=Convert.ToDecimal(lblTotalAdd.Text);
for (int i = 0; i <dgvSalesFooterAdd.Rows.Count ; i++)
{
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
}
lblFinalTotalAdd.Text = Total.ToString();
}
The exception is thrown when it does not find the Row index in i. You will have to reduce the number of rows by 1. This will tell the loop to count only the rows filled by values. Change the line
int i = 0; i <dgvSalesFooterAdd.Rows.Count
to
int i = 0; i <dgvSalesFooterAdd.Rows.Count - 1
Complete block will look like this;
for (int i = 0; i <dgvSalesFooterAdd.Rows.Count - 1; i++)
{
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
}

C# GUI application that stores an array and displays the highest and lowest numbers by clicking a button

Background:This is updated from 13 hours ago as I have been researching and experimenting with this for a few. I'm new to this programming arena so I'll be short, I'm teaching myself C# And I'm trying to learn how to have integers from a user's input into a textbox get calculated from a button1_Click to appear on the form. Yes, this is a class assignment but I think I have a good handle on some of this but not all of it; that's why I'm turning to you guys.
Problem:
I'm using Microsoft Visual Studio 2010 in C# language, Windows Forms Application and I need to create a GUI that allows a user to enter in 10 integer values that will be stored in an array called from a button_Click object. These values will display the highest and lowest values that the user inputted. The only thing is that the array must be declared above the Click() method.
This is what I have come up with so far:
namespace SmallAndLargeGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void inputText_TextChanged(object sender, EventArgs e)
{
this.Text = inputText.Text;
}
public void submitButton_Click(object sender, EventArgs e)
{
int userValue;
if(int.TryParse(inputText.Text, out userValue))
{
}
else
{
MessageBox.Show("Please enter a valid integer into the text box.");
}
int x;
x = Convert.x.ToString();
int squaredResults = squared(x);
int cubedResults = cubed(x); squared(x);
squaredLabel.Text = x.ToString() + " squared is " + squaredResults.ToString();
cubedLabel.Text = x.ToString() + " cubed is " + cubedResults.ToString();
}
public static int squared(int x)
{
x = x * x;
return x;
}
public static int cubed(int x)
{
x = x * squared(x);
return x;
}
}
}
Now I can't run this program because line 38 shows an error message of: 'System.Convert' does not contain a definition for 'x' Also I still have to have an array that holds 10 integers from a textbox and is declared above the Click() method. Please guys, any help for me? This was due yesterday.
This looks like homework, so you should try a bit more than that. Here is what you could do: parse the string (say it's a comma-separated list of numbers), cast each value to int and populate your array. You can either call .Max() / .Min() methods or loop through the values of the array and get the max / min value. Here is a bit of code:
int n = 10;
int[] numbers = (from sn in System.Text.RegularExpressions.Regex.Split(inputText.Text, #"\s*,\s*") select int.Parse(sn)).ToArray();
int max = numbers.Max();
int min = numbers.Min();
//int max = numbers[0];
//int min = numbers[0];
//for(int i = 1; i < n; i++)
//{
// if(max < numbers[i])
// {
// max = numbers[i];
// }
// if(min > numbers[i])
// {
// min = numbers[i];
// }
//}
This in all probability being a homework I will not provide entire solution but just provide a hint.
Task to me seems to be to some how accept 10 integers and then show smallest and largest of them. For this there is no need to maintain an array (off-course only if maintaining an array is itself not part of the problem). You just need to keep track of current minimum and current maximum.
As and when you receive an input compare it with the current minimum and maximum and update them accordingly. e.g.
if(num < curr_min) curr_min = num;

Categories