Reputation: 11
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.
Upvotes: 0
Views: 3189
Reputation: 17600
RowsAdded
may be fired once after x rows were added to DataGridView
(as name suggests). In event args passed to method you have property RowCount
to see for how many rows this event has been just fired.
Try this code:
private void itemsDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
if (e.RowIndex == -1 || e.RowCount == 0)
{
return;
}
for (int i = 0; i < e.RowCount; i++)
{
var index = e.RowIndex + i; //get row index
DataGridViewRow row = itemsDataGridView.Rows[index];
row.Cells["subTotalCol"].Value = ComputeRowSubTotal(row).ToString("c");
}
}
Upvotes: 1