c# - Calculating cells values in a DataGrid -
i have following datagrid (written in romanian):
i want calculate column "valoarea" formula:
valoarea = cantitatea * pret unitar (fara t.v.a.)
my actual code gives me error:
private void produsefacturate_cellvaluechanged(object sender, datagridviewcelleventargs e) { switch (e.columnindex) { case 3: var row = produsefacturate.rows[e.rowindex]; double qty, price; double.tryparse(row.cells[2].value.tostring(), out qty); double.tryparse(row.cells[3].value.tostring(), out price); row.cells[4].value = (qty * price).tostring(); break; } }
now, question is: how can populate specific cell on row data?
i'm assuming control datagridview?
you override cellformatting event. here's simple example:
i created datagridview 3 columns.
this.column1 = new system.windows.forms.datagridviewtextboxcolumn(); this.column2 = new system.windows.forms.datagridviewtextboxcolumn(); this.column3 = new system.windows.forms.datagridviewtextboxcolumn(); this.datagridview1.columns.addrange(new system.windows.forms.datagridviewcolumn[] { this.column1, this.column2, this.column3}); this.datagridview1.name = "datagridview1"; this.datagridview1.size = new system.drawing.size(405, 150); this.datagridview1.tabindex = 1; this.datagridview1.cellformatting += new system.windows.forms.datagridviewcellformattingeventhandler(this.datagridview1_cellformatting);
and want make 3rd column product of first two. here's method override cellformatting.
private void datagridview1_cellformatting(object sender, datagridviewcellformattingeventargs e) { if (this.datagridview1.columns[e.columnindex].name.equals("column3")) { try { this.datagridview1.rows[e.rowindex].cells[2].value = convert.toint32(this.datagridview1.rows[e.rowindex].cells[0].value) * convert.toint32(this.datagridview1.rows[e.rowindex].cells[1].value); } catch (exception ex) { } } }
note whenever change value in 1st 2 columns, 3rd recalculated.
Comments
Post a Comment