mah*_*naz 26 c# datagridview winforms
我需要显示此count列的总和datagridview,但我不知道如何获取datagridview中的数据.
当我按一下按钮,我想展示94在label1.
如何才能做到这一点?

Jam*_*MLV 35
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();
Run Code Online (Sandbox Code Playgroud)
Nat*_*ski 18
使用LINQ快速而干净的方式
int total = dataGridView1.Rows.Cast<DataGridViewRow>()
.Sum(t => Convert.ToInt32(t.Cells[1].Value));
Run Code Online (Sandbox Code Playgroud)
在VS2013上验证
Dan*_*Tao 15
如果您的网格绑定了a DataTable,我相信您可以这样做:
// Should probably add a DBNull check for safety; but you get the idea.
long sum = (long)table.Compute("Sum(count)", "True");
Run Code Online (Sandbox Code Playgroud)
如果它没有绑定到表,你可以轻松地这样做:
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;
Run Code Online (Sandbox Code Playgroud)
如果可以,请使用LINQ.
label1.Text = dataGridView1.Rows.Cast<DataGridViewRow>()
.AsEnumerable()
.Sum(x => int.Parse(x.Cells[1].Value.ToString()))
.ToString();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
97925 次 |
| 最近记录: |