how I can show the sum of in a datagridview column?
I need t开发者_运维知识库o show the sum of the count
column from this datagridview
, but I don't know how I can get to the data in the datagridview.
When I click on the button, I want to show 94
in label1
.
How can this be done?
int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
}
label1.Text = sum.ToString();
Fast and clean way using LINQ
int total = dataGridView1.Rows.Cast<DataGridViewRow>()
.Sum(t => Convert.ToInt32(t.Cells[1].Value));
verified on VS2013
If your grid is bound to a DataTable
, I believe you can just do:
// Should probably add a DBNull check for safety; but you get the idea.
long sum = (long)table.Compute("Sum(count)", "True");
If it isn't bound to a table, you could easily make it so:
var table = new DataTable();
table.Columns.Add("type", typeof(string));
table.Columns.Add("count", typeof(int));
// This will automatically create the DataGridView's columns.
dataGridView.DataSource = table;
Use LINQ if you can.
label1.Text = dataGridView1.Rows.Cast<DataGridViewRow>()
.AsEnumerable()
.Sum(x => int.Parse(x.Cells[1].Value.ToString()))
.ToString();
decimal Total = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
Total+= Convert.ToDecimal(dataGridView1.Rows[i].Cells["ColumnName"].Value);
}
labelName.Text = Total.ToString();
Add the total row to your data collection that will be bound to the grid.
you can do it better with two datagridview, you add the same datasource , hide the headers of the second, set the height of the second = to the height of the rows of the first, turn off all resizable atributes of the second, synchronize the scrollbars of both, only horizontal, put the second on the botton of the first etc.
take a look:
dgv3.ColumnHeadersVisible = false;
dgv3.Height = dgv1.Rows[0].Height;
dgv3.Location = new Point(Xdgvx, this.dgv1.Height - dgv3.Height - SystemInformation.HorizontalScrollBarHeight);
dgv3.Width = dgv1.Width;
private void dgv1_Scroll(object sender, ScrollEventArgs e)
{
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
{
dgv3.HorizontalScrollingOffset = e.NewValue;
}
}
//declare the total variable
int total = 0;
//loop through the datagrid and sum the column
for(int i=0;i<datagridview1.Rows.Count;i++)
{
double.TryParse(datagridview1.Rows[i].Cells["CELL NAME OR INDEX"].Value.ToString(),out int cellValue)
total +=total;
}
//you can use the total here
lblTotal.Text = total.ToString();
So, you can accomplish this by Using LINQ like so the next code
label1.Text = (from DataGridViewRow row in datagridview1.Rows
where !String.IsNullOrEmpty(row.Cells[1].FormattedValue.ToString())
select Convert.ToDouble(row.Cells[1].FormattedValue)).Sum().ToString();
精彩评论