首页 > 解决方案 > 第一次后无法在datagridview单元格C#中输入浮点数(在为每一行计算小计之后)

问题描述

我在 C# 中有一个 datagirdview,您输入产品的价格和数量,它会自动计算该产品的小计,我修改了价格的单元格以输入整数和浮点数,并修改单元格以输入整数和浮点数。在计算小计之前,用户可以完美地为数量编写浮点单元格以仅输入整数,但是在计算该行的小计之后,它不允许您输入浮点数,它只允许整数。我查看了许多来源,但找不到解决方案。请帮我解决这个我非常感激的错误。

这是gridview的屏幕截图, 在此处输入图像描述 您可以看到我在第4列中输入了一个浮点数,但那是在计算第8列中的小计之前。这是我在列中输入浮点数和整数的代码

 private void dgvpurchase_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
        if (dgvpurchase.CurrentCell.ColumnIndex == 4 || dgvpurchase.CurrentCell.ColumnIndex == 5) //Desired Column
        {
            TextBox tb = e.Control as TextBox;
            if (tb != null)
            {
                tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
            }
        }
        if (dgvpurchase.CurrentCell.ColumnIndex == 6 || dgvpurchase.CurrentCell.ColumnIndex == 7)
        {
            TextBox tb = e.Control as TextBox;
            if (tb != null)
            {
                tb.KeyPress += new KeyPressEventHandler(Column2_KeyPress);
            }
        }
    }
    //allowing real and float numbers for price columns
    private void Column1_KeyPress(object sender, KeyPressEventArgs e)

    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
        {
            e.Handled = true;
        }

        // allow 1 dot:
        if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
        {
            e.Handled = true;
        }

    }

    //allowing only int number of column quantity and bonuus
    private void Column2_KeyPress(object sender, KeyPressEventArgs e)

    {

        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }
    }

这是计算每个产品小计的代码

private void CalculateAll() {
        try
        {
            total_all = 0;

            for (int i = 0; i < dgvpurchase.Rows.Count - 1; i++)
            {
                if (dgvpurchase.Rows[i].Cells[4].Value == null)
                {

                }
                double price = float.Parse(dgvpurchase.Rows[i].Cells[4].Value.ToString());
                double quantity = float.Parse(dgvpurchase.Rows[i].Cells[6].Value.ToString());
                double subtotal = price * quantity;
                dgvpurchase.Rows[i].Cells[8].Value = Math.Round(subtotal, 3, MidpointRounding.ToEven);
                total_all += subtotal;

            }
            // total_all=Math. total_all
            txttotalall.Text = Math.Round(total_all,3,MidpointRounding.ToEven).ToString();
            }

我在数据网格视图的 CellEndEdit 事件中调用了这个方法,这是代码

 private void dgvpurchase_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
            CalculateAll();    
    }

拜托,你能找出问题所在吗?我真的很感激。

标签: c#datagridviewdatagriddatagridviewcolumn

解决方案


推荐阅读