Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
How can I show the sum from datagri2 column to label

I tried more than one code and the value appears as zero

I hope for a solution, thank you

What I have tried:

Dim total As String = 0
       For t As Integer = 0 To Datagrid2.Columns.Count - 1
           total = Val(Datagrid2.Items(t).Cells(5).Text)
       Next


       Label14.Text = total
Posted
Comments
Graeme_Grant 14-Oct-23 5:14am    
"I want a solution to this problem" is not a very nice way of asking for help.

Several problems here:
1) You are looping through all columns, but accessing the rows with the index, with a fixed column. If you have 4 rows and 6 columns, your app will fail.
You should be using the rows count, not the columns.

2) Inside the loop, you overwrite the total with the new value each time, discarding any previous value. As a result, you end up with the value of only final row accessed in total
Add the row / column value to the total inside the loop instead.

3) Don't use "magic numbers" like 5 to access a specific column: use column names, or create a named constant and use that instead. If you add, remove, or reorder columns later, you will miss some of the magic numbers and it gets difficult to spot your error.
 
Share this answer
 
Comments
yossef2023 14-Oct-23 1:32am    
Sorry, I don't understand what you mean. Please clarify, thank you
OriginalGriff 14-Oct-23 2:01am    
Which part do you not understand?
yossef2023 14-Oct-23 2:12am    
Sorry, all parts
OriginalGriff 14-Oct-23 2:28am    
You are kidding, right?
"Add the row / column value to the total inside the loop instead." makes no sense to you?
How did you manage to create what code you have?
Because you don't understood what OG has mentioned :

Supposing that your code is basicly correct you should change minimum the following :
VB
Dim total As DOUBLE = 0     ' <- Changes here
       For t As Integer = 0 To Datagrid2.Columns.Count - 1
           total += cdbl(Datagrid2.Items(t).Cells(5).Text)     ' <- Changes here
       Next


       Label14.Text = total.toString     ' <- Changes here


- you can't add a Value inside a String
- if you want to have a total you should sum it ...
 
Share this answer
 
v3
Comments
yossef2023 14-Oct-23 6:23am    
The code didn't work
Ralf Meier 14-Oct-23 7:37am    
what part of it doesn't work ?
Have you ever checked that you are working with the correct Cell inside your DataGrid ?
Set a Breakpoint at the Position of "next" and look with the DEBUGGER which result you get ...
Ralf Meier 14-Oct-23 8:29am    
Have you ever read what OG has written in his Solution ? Here I mean at first of all his Point 1)

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