Click here to Skip to main content
15,899,313 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I cannot get the value to string from a datagridview in a for loop. This code returns empty string.

VB
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
       Dim s, r As String
       Dim es As Char
       Dim f, i As Integer
       For i = 0 To DataGridView1.RowCount - 1
       s = System.Convert.ToString(DataGridView1.Rows(i).Cells(0).Value)
           TextBox1.Text = s 's is empty
                  Next
   End Sub

without the for loop it gets the value of the cell
Posted
Comments
[no name] 15-Jul-15 15:10pm    
s = DataGridView1.Rows(i).Cells(0).Value.ToString()
Sergey Alexandrovich Kryukov 15-Jul-15 17:48pm    
5ed!
More seriously, I answered the "question" (amazing one :-), please see.
—SA

1 solution

Not true: your code does not return anything. This is a method (Sub), probably used as an event handler; it does not return anything but uses some side effect, which is the assignment of some string value to TextBox1.Text (never ever use such names; never ever use auto-generated names which comes from the designer; they violate Microsoft naming conventions and does not carry any semantic meaning; always renames all such members).

Please see the comment to the question by Wes Aday. This is all you need to know.

Now, your loop is totally pointless. It's effect is equivalent to just one assignment:
VB
TextBox1.Text = DataGridView1.Rows(DataGridView1.RowCount - 1).Cells(0).ToString()
As to the values you assigned on all the iterations of your loop, they are all lost (all but one), because you replace it with the value in next iteration. Only the value in the very last iterations remains in the value of TextBox1.Text. Isn't that obvious. And, if your observations are correct, the values assigned in last iteration is empty string. Perhaps this is just a cell with not yet entered data. As simple as that.

That's all.

—SA
 
Share this answer
 
v7
Comments
Member 3892343 16-Jul-15 4:13am    
about last string remain from the loop I have more code and not a textbox, about .tostring you're right

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