本文介绍了如何在文本框中动态获取datagridview列的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取 datagridview 列的总和并将其显示在文本框中.每次输入后,应动态更改总和.为此,我正在使用文本框的 textChanged 事件,但是当输入时它不显示任何结果.我想在文本框中动态获取结果.我想避免使用按钮进行求和.

I want to get the sum of a column of datagridview and show that in textbox. After each entry the sum should be changed dynamically. For that I am using textChanged event of a textbox but when the entry is made it does not show any result. I want to get the result dynamically in the textbox. I want to avoid the use of button for sum.

这是文本框 textChanged 事件的一段代码:

Here is a piece of code for the textbox textChanged event:

private void textBox9_TextChanged(object sender, EventArgs e)
        {
            double sum = 0;
            for (int i = 0; i < dataGridView2.Rows.Count; ++i)
            {
                sum += Convert.ToDouble(dataGridView2.Rows[i].Cells[5].Value);
            }
            textBox9.Text = sum.ToString();
        }

推荐答案

你的代码是正确的,但我把它放在 CellValueChanged 事件中并检查以确保它与你正在寻找的单元格相同为了.如果单元格的值发生变化,或者如果添加了新行并随后获得了分配的值,这将被触发.

You've got your code right, but instead I've put it in the CellValueChanged event and check to make sure it was the same cell you're looking for. This will get fired if the cell's value changes, or if a new row is added and subsequently gets a value assigned.

    private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 5)
            textBox9.Text = CellSum().ToString();
    }

    private double CellSum()
    {
        double sum = 0;
        for (int i = 0; i < dataGridView2.Rows.Count; ++i)
        {
            double d = 0;
            Double.TryParse(dataGridView2.Rows[i].Cells[5].Value.ToString(), out d);
            sum += d;
        }
        return sum;
    }

我将您的逻辑拆分为一个单独的方法,因此如果您想获得其他内容的总和,您可以简单地调用该方法.我想你可以只阅读 textbox.Text,但是...

I split up your logic into a separate method, so incase you ever want to get the sum for something else, you can simply call that method. I suppose you could just read textbox.Text, but...

我还使用了 Double.TryParse,因为它提供了一些基本保护,以防给定单元格中的值实际上不是数字.我不知道数据的来源是什么(用户输入/来自外部来源?)所以我想我会添加一些保护.

I've also used Double.TryParse as it provides some basic protection incase the value in that given cell is not actually a number. I don't know what the source of the data is (user entered / from an outside source?) so I figured I'd add a little protection.

编辑 Grant 提出了一个很好的观点,编辑了我的解决方案以包含正在修改的单元格值.我使用了 CellValueChanged 事件而不是 CellEndEdit,以防用户以外的其他东西可以更改其值.

Edit Grant raises a great point, editted my solution to include cell value being modified. I used the CellValueChanged event instead of CellEndEdit, incase something other than the user can change its value.

这篇关于如何在文本框中动态获取datagridview列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 22:54