日期:2014-05-17  浏览次数:20923 次

C#中处理datagridview中显示的数据
我用如下代码计算datagridview中查询到的数据某列的和,运行老是报错:输入字符串的格式不正确。
我不知道错在哪了?请大侠们帮忙看看
float jz = 0,sz=0;
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                
               jz += float.Parse(dataGridView1.Rows[i].Cells[12].Value.ToString());
              
                sz += float.Parse(dataGridView1.Rows[i].Cells[14].Value.ToString());
                
            }
c# datagridview

------解决方案--------------------
加上
MessageBox.Show(dataGridView1.Rows[i].Cells[12].Value.ToString());
MessageBox.Show(dataGridView1.Rows[i].Cells[14].Value.ToString());

输出什么,是否是合法的数字,前后是否有空格?
------解决方案--------------------
很有可能dataGridView1.Rows[i].Cells[12].Value.ToString()的结果就不是“123.45”这样的结果,有可能就是一个null或者是""或者是"kkk"。转换的时候就报输入字符串的格式不正确的错误。
------解决方案--------------------
 float num=0;
 float num1=0;

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
             {
                float.TryParse(dataGridView1.Rows[i].Cells[12].Value.ToString(),out num);
                jz += num
                float.TryParse(dataGridView1.Rows[i].Cells[14].Value.ToString(),out num1);
                 sz +=num1