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();
}
Related
I'm working on a POS winforms application, and I'm having trouble, the datagridview is filled by user input, through a barcode scanner, and then the user adjusts the Quantity inside the data grid view, what I want to do is when the user changes the value of Quantity ( which is set to 1 by default) it gets multiplied by second column which is price and show the result in the third column
Column A (value entered) x Column B = Result to Column C
I've tried using this code, but no luck
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
int a =dataGridView1.Rows[i][0].value;
int b =dataGridView1.Rows[i][1].value;
int c = a*b;
c=dataGridView1.Rows[i][2].value;
}
it gave me Error 14 Cannot apply indexing with [] to an expression of type 'System.Windows.Forms.DataGridViewRow'
You need to use the Cells property of the DataGridViewRow class
Use:
int a = dataGridView1.Rows[i].Cells[0].Value;
int b = dataGridView1.Rows[i].Cells[1].Value;
int c = a * b;
dataGridView1.Rows[i].Cells[2].Value = c;
Please note, I change the last line to be dataGridView1.Rows[i].Cells[2].Value = c; as that seems to match your question...you want the answer stored in the cell.
decimal s = Convert.ToDecimal(dataGridView_DaginaAdd_SellInovice.CurrentRow.Cells[10].Value);
decimal s1 = Convert.ToDecimal(dataGridView_DaginaAdd_SellInovice.CurrentRow.Cells[11].Value);
decimal s13 = s + s1; Convert.ToDecimal(dataGridView_DaginaAdd_SellInovice.CurrentRow.Cells[12].Value = s13);
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);
}
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);
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);
}
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();