【问题标题】:retrieving number value from datagridview C#从datagridview C#中检索数值
【发布时间】:2014-07-05 20:03:23
【问题描述】:

我正在尝试从 datagridview 中检索数值。表中的值和变量 (weeklyTotal) 的数据类型都是整数。我也试图将它转换为整数。我浏览了整个网站以寻找类似的问题,但没有一个解决方案有帮助。我得到的错误信息是“当转换一个数字时,值必须小于无穷大”。我不止一次回到我的桌子上,以确保我没有无效值。

这是一个运行时错误,IDE 总是指向这一行

weeklyTotal += (int)dataGridView1.Rows[i].Cells[1].Value;

for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
        {
            sdate = dataGridView1.Rows[i].Cells[2].Value.ToString();
            ddate = dataGridView1.Rows[i].Cells[3].Value.ToString();

            if ((weekFirstDay <= Convert.ToInt32(sdate) &&
                Convert.ToInt32(sdate) <= (weekFirstDay + 7))||(weekFirstDay <= `Convert.ToInt32(ddate) &&`
                Convert.ToInt32(ddate) <= (weekFirstDay + 7)))
            {
                dataGridView1.Rows[i].Selected = true;
                dataGridView1.Rows[i].Visible = true;
                weeklyTotal += (int)dataGridView1.Rows[i].Cells[1].Value;

                //weeklyTotalString = dataGridView1.Rows[i].Cells[1].Value.ToString();
                //weeklyTotal += Convert.ToInt32(weeklyTotalString);


            }
            else

【问题讨论】:

    标签: c# datagridview runtime


    【解决方案1】:

    这是因为以下内容不会将您的单元格值转换为 int 类型:

    (int) dataGridView1.Rows[i].Cells[1].Value
    

    你只是在说“嘿编译器,请将它视为 int 类型”的字符串,但它仍然是下面的字符串类型。像之前一样使用Convert.ToInt32 方法。

    weeklyTotal += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
    

    【讨论】:

    • 我回去使用之前的代码 Convert.ToInt32。它似乎工作得更好。之所以发表评论,是因为它向我显示了一条错误消息。太感谢了。是否有另一种方法可以将 datagridview 中的值转换为字符串,然后再转换为数值?
    【解决方案2】:
    int num = Convert.ToInt32(dgv.Rows[i].Cells["col_name"].Value);
    

    【讨论】:

      【解决方案3】:

      您可能正在尝试对 DBNull 值进行 (int) 强制转换。我假设您使用数据库中的数据填充 datagridview。

      试试这个:

      if(dataGridView1.Rows[i].Cells[1].Value != DBNull.Value)
      {
          weeklyTotal += (int)dataGridView1.Rows[i].Cells[1].Value;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-02
        • 2019-09-02
        • 2016-10-21
        • 1970-01-01
        • 2016-05-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多