I need to 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?
This question is related to
c#
winforms
datagridview
Fast and clean way using LINQ
int total = dataGridView1.Rows.Cast<DataGridViewRow>()
.Sum(t => Convert.ToInt32(t.Cells[1].Value));
verified on VS2013
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;
}
}
Use LINQ if you can.
label1.Text = dataGridView1.Rows.Cast<DataGridViewRow>()
.AsEnumerable()
.Sum(x => int.Parse(x.Cells[1].Value.ToString()))
.ToString();
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;
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();
//declare the total variable
int total = 0;
//loop through the datagrid and sum the column
for(int i=0;i<datagridview1.Rows.Count;i++)
{
total +=int.Parse(datagridview1.Rows[i].Cells["CELL NAME OR INDEX"].Value.ToString());
}
string tota
Source: Stackoverflow.com