Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have tried as below given code. new column adding without any issue and not showing any errors also. but the problem is not showing any values, even manual typing also not holding. it was clearing itself once we come out from cell. Please help me. Thanks in advance.

What I have tried:

in Form_Shown(...) event:
VB
Dim tmpCol As New DataGridViewTextBoxColumn

tmpCol.Name = "Bal"
tmpCol.HeaderText = "Balance"
tmpCol.CellTemplate = New DataGridViewTextBoxCell

Me.DGV_Details.Columns.Insert(8, tmpCol)

For Each ro As DataGridViewRow In Me.DGV_Details.Rows
	Dim inc, exp As Double
	inc = ro.Cells("Income").Value
	exp = ro.Cells("Expence").Value
	ro.Cells("Bal").Value = inc - exp
Next
Posted
Updated 20-Apr-24 5:12am
v3
Comments
Dave Kreskowiak 6-Apr-24 13:13pm    
If your DGV is bound to a datasource, which it should always be, you have to add the column to the datasource, do that calculations there, and you can add a new column to the DGV and bind it to the new column in the datasource.

Start by using the debugger to find out exactly what values you are getting.: my guess would be that there are no rows of data yet (i.e. you haven't loaded the data into the DGV at that point) - but we have no idea how you set up your DGV and your data, so we can't tell.

It's probably a bad idea to do it that way anyway - you should use the underlying data source instead of modifying the DGV rows themselves (i.e. the DataTable or Collection that you load the DGV from, preferably by binding it to the DGV) as it means that adding filtering / sorting to the data at a later date becomes considerably easier.

If I try it here by adding a column to a databound DGV and then processing each row after the DataSource has been set, it works fine (except I obviously have to cope with the blank row at the end).
 
Share this answer
 
v2
I'd suggest to read this: DataColumn.Expression Property (System.Data) | Microsoft Learn[^]
This is a very easy way to create computed column :)

See:
VB.NET
Dim dt As DataTable = New DataTable()
dt.Columns.Add("id", Type.GetType("System.Int32"))
dt.Columns.Add("price", Type.GetType("System.Decimal"))
dt.Columns.Add("tax", Type.GetType("System.Decimal"))
Dim cc = dt.Columns.Add("priceandtax", Type.GetType("System.Decimal"))
cc.Expression = "price + (price * tax)"

dt.Rows.Add(1, 50.0, 0.08)
dt.Rows.Add(2, 50.0, 0.22)
dt.Rows.Add(8, 20, 0.05)
dt.Rows.Add(9, 20, 0.03)
DataGridView1.DataSource = dt
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900