[英]how I can show the sum of in a datagridview column?
我需要顯示此datagridview
count
列的總和,但我不知道如何獲取 datagridview 中的數據。
當我點擊按鈕時,我想在label1
顯示94
。
如何做到這一點?
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();
使用 LINQ 的快速而干凈的方式
int total = dataGridView1.Rows.Cast<DataGridViewRow>()
.Sum(t => Convert.ToInt32(t.Cells[1].Value));
在 VS2013 上驗證
如果您的網格綁定到DataTable
,我相信您可以這樣做:
// Should probably add a DBNull check for safety; but you get the idea.
long sum = (long)table.Compute("Sum(count)", "True");
如果它沒有綁定到一個表,你可以很容易地做到這一點:
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;
如果可以,請使用 LINQ。
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();
將總行添加到將綁定到網格的數據集合。
您可以使用兩個 datagridview 做得更好,添加相同的數據源,隱藏第二個的標題,將第二個的高度設置為第一個的行的高度,關閉第二個的所有可調整大小的屬性,同步兩者的滾動條,只有水平的,把第二個放在第一個的底部等等。
看看:
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++)
{
total +=int.Parse(datagridview1.Rows[i].Cells["CELL NAME OR INDEX"].Value.ToString());
}
string tota
使用LINQ很干凈
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.