Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何计算一个datagrid列中所有行的值_C#_Datagrid - Fatal编程技术网

C# 如何计算一个datagrid列中所有行的值

C# 如何计算一个datagrid列中所有行的值,c#,datagrid,C#,Datagrid,我有这个代码试图让它工作,但它只是不起作用 private void Izračunaj_Click(object sender, EventArgs e) //it calculates value on click { int total; foreach(dataGridView1 column in dataGridView1.Rows()) // { total = total + int32.Parse(column[2].ToString(

我有这个代码试图让它工作,但它只是不起作用

private void Izračunaj_Click(object sender, EventArgs e)  //it calculates value on click
{
    int total;
    foreach(dataGridView1 column in dataGridView1.Rows()) // 
    {
       total = total + int32.Parse(column[2].ToString()); 
    } 
    textbox text = total; // want to have calculated value displayed in a text box
}
我得到的错误是:

非发票成员“System.Windows.Forms.DataGridView.Rows”不能像方法一样使用

我只是不知道我需要在那里使用哪种语法。

是一个属性,您使用的是指定方法的
()
。只需拆下支架

foreach(dataGridView1 column in dataGridView1.Rows)  //No ()
如果要使用LINQ,则可以执行以下操作:

total = dataGridView1.Rows
                .OfType<DataGridViewRow>()
                .Sum(r => Convert.ToInt32(r.Cells[2]));

我认为它应该解决你的问题

int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
    sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
}
int和=0;
对于(int i=0;i
它的数据源是什么?您应该使用该选项。datasource是在数据中键入的datagrid,还是从textfile导入的。必须将其显示在文本框中吗?它没有在文本框中显示计算数据,我只是在您的最后一行代码后添加了以下代码:“string texxt=total.ToString();textBox1.text=texxt;”@mateoZD,我在回答中没有涵盖这一部分,假设这不是您出错的原因。但现在我已经编辑了这个问题的细节。
int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
    sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
}