1

I have a simple form with datagridview and textbox. In datagridview, there are select (checkbox), item name, quantity, and price column. When I check the item name in datagridview, it will calculate the total and display it in the textbox, but it isn't updated directly. I must click another column to update the value.

How to update the total directly when I check the item in datagridview without click another column to update the value?

public partial class Form1 : Form
{
    //BindingList<Item> items = new BindingList<Item>();
    BindingSource items = new BindingSource();

    public Form1()
    {
        InitializeComponent();

        items.Add(new Item { Select = false, Name = "A", Quantity = 1, Price = 10000 });
        items.Add(new Item { Select = false, Name = "B", Quantity = 2, Price = 20000 });

        dataGridView1.DataSource = items;
    }

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        decimal total = 0;

        foreach (Item item in items)
        {
            if (item.Select)
            {
                total += (item.Quantity * item.Price);
            }
        }

        textBox1.Text = total.ToString();
    }
}

public class Item
{
    public bool Select { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
}
Willy
  • 1,689
  • 7
  • 36
  • 79

0 Answers0