I have a datagridview that is bound to a dataSource and is updated upon loading the form. The datagridview also contains one unbound column caled subTotal which multiples 3 values in a row. Binding of dataSource works fine and the DGV is updated correctly together with the unbound column's values. However, after the Form_Load Event is finished, the program automatically deletes all the rows in my DGV and re-Adds all the items in my DataSource into the DGV on its own. My problem is after re-adding the rows, the subTotal column is only updated for the first 2 rows and the next rows' subTotal column values are set to null. My test case includes a DataTable containing more than 2 rows and no matter how many rows I have, only the first 2 rows' subTotal is being computed.
Could anyone provide me a possible solution and explain why the program automatically removes and re-adds the binded rows to the datagridview and how come only the first 2 rows are being computed? I've been working on this for hours and still couldn't find a solution for my problem.
Thanks!
Here are my codes:
private void ShowSalesOrderWindow_Load(object sender, EventArgs e)
{
CreateItemsTable();
itemsDataGridView.AutoGenerateColumns = true;
itemsDataGridView.DataSource = itemTable;
CreateSubTotalColumn();
GenerateItemsDataTable();
}
private void CreateSubTotalColumn()
{
DataGridViewColumn subTotalCol =
new DataGridViewTextBoxColumn();
subTotalCol.Name = "subTotalCol";
subTotalCol.HeaderText = "Sub-Total";
subTotalCol.ReadOnly = true;
itemsDataGridView.Columns.Insert(4, subTotalCol);
}
private void GenerateItemDataTable()
{
foreach (SalesOrderItem soi in salesOrder.SalesOrderItems)
{
DataRow row = itemTable.NewRow();
row["Product Code"] = soi.Product.ProductCode;
row["Quantity"] = soi.Quantity;
row["Price"] = soi.Price;
row["Discount"] = soi.Discount;
itemTable.Rows.Add(row);
}
}
private void itemsDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
DataGridViewRow row = itemsDataGridView.Rows[e.RowIndex];
row.Cells["subTotalCol"].Value = ComputeRowSubTotal(row).ToString("c");
}
I also created an empty event handler for the RowsRemoved event just to add a breakpoint and see if it enters it.