【问题标题】:Problem when summing selected cells in DataGridview在 DataGridview 中对选定单元格求和时出现问题
【发布时间】:2011-05-19 16:55:32
【问题描述】:

我将此代码用于汇总选定的单元格。它工作得很好,但是当用户选择单元格中的字母时会抛出异常:) 当在选择单元格中时,我如何确保字母不求和

【问题讨论】:

  • 邮政编码。接受更多答案。

标签: c# winforms datagrid


【解决方案1】:
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) 
    { 
        String filterStatus = DataGridViewAutoFilterColumnHeaderCell.GetFilterStatus(dataGridView1); 
        if (String.IsNullOrEmpty(filterStatus)) 
        { 
            showAllLabel.Visible = false; 
            filterStatusLabel.Visible = false; 
        } 
        else 
        { 
            int result = -1;
            Int32.TryParse(filterStatus, out result);
            if (result != 0)
            {
                 // it is a number
                 showAllLabel.Visible = true; 
                 filterStatusLabel.Visible = true; 
                 filterStatusLabel.Text = filterStatus; 
            }
            else
            {
                 // it can be a number yet won't help you with adding
            }
        } 
    }

【讨论】:

  • 您应该查看 TryParse 的返回值而不是结果(因为零是一个数字!)
  • private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { String filterStatus = DataGridViewAutoFilterColumnHeaderCell.GetFilterStatus(dataGridView1); if (String.IsNullOrEmpty(filterStatus)) { showAllLabel.Visible = false; filterStatusLabel.Visible = 假; } 其他 { showAllLabel.Visible = true; filterStatusLabel.Visible = true; filterStatusLabel.Text = 过滤器状态; } }
  • @Pabuc:Stuart 是对的,如果过滤器状态是 "0" 你的代码跳过它,但 0 是一个数字。你应该得到bool isNum = Int32.TryParse(filterStatus, out result) 并在你的if 中使用isNum
  • 是的,它会跳过它,但为什么要在总和中加 0? x + 0 = x 反正??
  • 是的,在这种情况下是可以的,但是如果,例如,这个代码被重用于计算Average 呢?
【解决方案2】:

这是我的代码

 private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        String filterStatus = DataGridViewAutoFilterColumnHeaderCell.GetFilterStatus(dataGridView1);
        if (String.IsNullOrEmpty(filterStatus))
        {
            showAllLabel.Visible = false;
            filterStatusLabel.Visible = false;
        }
        else
        {
            showAllLabel.Visible = true;
            filterStatusLabel.Visible = true;
            filterStatusLabel.Text = filterStatus;
        }
    }

【讨论】:

  • 你这里没有总结什么吗?我已经编辑了我的代码,但不确定这是否是您需要的......
  • 是的 Pabuc 是对的,你没有在这里求和。顺便说一句,您在此答案的最后一次编辑中看到了我附加的过滤器示例项目吗? --> stackoverflow.com/questions/4243616/…
猜你喜欢
  • 2021-07-18
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
  • 1970-01-01
  • 2012-05-10
  • 1970-01-01
相关资源
最近更新 更多