c# - DataGridView 单元格编辑结束事件

标签 c# .net winforms datagridview

我有一个 DataGridView,其中有一列“总计”。 DataGridView 是可编辑的。在 GridView 下方,我有一个文本框,其中我想要网格“总计”列的总计。我所做的是,当用户进入网格中的总计列时,它会反射(reflect)到 GridView 下方的总文本字段中。为了在文本字段中显示总计,我添加了 GridView 的总计列。但问题是,如果我第一次进入 GridView 的总列,它会立即反射(reflect)到下面的文本字段中。但是,如果我在 DataGridView 的总列中编辑相同的值,则网格下方的文本字段会将其与以前的值一起添加到文本字段中我想要新编辑值的位置。如何解决这个问题?以下是代码:-

private void grdCaret_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    try
    {  
        string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        if (e.ColumnIndex == 1)
        {
           // int val = int.Parse(value);
           // quantity = val;
           // ekundag = ekundag + quantity;
           //tbTotDag_cr.Text =ekundag.ToString();

            int quantity = 0;

            foreach (DataGridViewRow row in grdCaret.Rows)
                quantity +=(int) grdCaret.Rows[e.RowIndex].Cells[1].Value.ToString();
                //quantity +=(int) row.Cells[1].Value;

            tbTotDag_cr.Text = quantity.ToString();
        }

        if (e.ColumnIndex == 2)
        {
            float val = float.Parse(value);
            total = val;
            ekunrakam = ekunrakam + total;
            tbTotPrice_cr.Text = ekunrakam.ToString();
        }
        grdCaret.Columns[3].ReadOnly = false;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
}

最佳答案

使用 CellEndEdit 事件来更新你的总值:

private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    int total = 0;

    foreach (DataGridViewRow row in dataGridView.Rows)            
        total += (int)row.Cells[columnTotal.Index].Value;

    totalTextBox.Text = total.ToString();           
}

关于c# - DataGridView 单元格编辑结束事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11028405/

相关文章:

c# - Knockout js 和 Raven DB

c# - DateTime.Now 与 DateTime.UtcNow 用法的区别

c# - 控制音量混合器

c# - 如何对 ToolStripDropDownButton 的 DropDownMenu 上的鼠标滚轮使用react?

c# - 在 ListView 中更改颜色线

c# - 如何在不使用 c# 中的 for 或 foreach 循环的情况下使用数据表从特定的 mysql 表中获取每个值?

c# - 比较两个相同结构的任意 JToken-s

c# - 为什么这段代码不会死锁?

winforms - F# 使用 Winforms DataVisualization 制作条形图

c# - 如何使用 foreach 循环制作多线程应用程序