想要对gridview行中的数据求和并在文本框中获取结果.提前thanX [英] want to sum data in rows of gridview and get result in text box. thanX in advance

查看:86
本文介绍了想要对gridview行中的数据求和并在文本框中获取结果.提前thanX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void button2_Click(object sender, EventArgs e)
       {
           for (int i = 0; i <= dataGridView1.Rows.Count; i++)
           {
               int sum = 0 ;

               sum = sum + Convert.ToInt32(dataGridView1.Rows[i].Cells[i].Value);
               textBox2.Text = Convert.ToString(sum);
           }
       }

推荐答案

当然,您的代码无法正常工作,因为您只是简单地告诉程序获取第一行第一单元格和第二行第二单元格的总和,等等. ...
如果行数多于列数,您会在一分钟内得到错误消息
您需要添加另一个for循环以遍历每一行中的单元格,这就是它的工作方式

希望这对您有帮助
Of course your code wont work because simply you telling the program to get the sum of the first row first cell and second row second cell etc...
and in one point you will get an error if your rows are more than your columns
you need to add another for loop to loop over the cells in each row this is how its going to work

Hope this helped


更好的方法是

1.有一个表单级变量来存储总和
2.初始化为0
3.然后在RowDatBound 事件中,将当前行值添加到该成员变量中.

当网格绑定时,该变量将包含总和.

4.您可以将该值放在取消事件的文本框中.
The better way to do this would be to

1. have a form level variable to store the sum,
2. initialize it to 0
3. and then in RowDatBound event add the current rows value into this member variable.

When the grid is bound this varable will contain the sum.

4. you can put this value in a textbox in unlod event.


这篇关于想要对gridview行中的数据求和并在文本框中获取结果.提前thanX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆