for循环中datagridview中的字符串为空 [英] string in datagridview in for loop is empty
问题描述
我无法在for循环中从datagridview获取该值到字符串.此代码返回空字符串.
I cannot get the value to string from a datagridview in a for loop. This code returns empty string.
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
如果没有for循环,它将获取单元格的值.
without the for loop it gets the value of the cell
推荐答案
不正确:您的代码不返回任何内容.这是一个方法(Sub),可能用作事件处理程序;它不返回任何东西,而是使用一些副作用,即将某些字符串值分配给TextBox1.Text
(从不使用此类名称;从不使用设计者提供的自动生成的名称;它们违反了Microsoft的命名约定,并且不具有任何语义含义;始终重命名所有此类成员).
请参阅Wes Aday对问题的评论.这就是您需要知道的全部内容.
现在,您的循环完全没有意义.它的效果只相当于一项任务:
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 toTextBox1.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:
TextBox1.Text = DataGridView1.Rows(DataGridView1.RowCount - 1).Cells(0).ToString()
对于您在循环的所有迭代中分配的值,它们都会丢失(除一个以外的所有值),因为您将其替换为下一次迭代中的值.只有最后一次迭代中的值保留在TextBox1.Text
的值中.这不是很明显.并且,如果您的观察结果正确,那么上次迭代中分配的值将为空字符串.也许这只是一个尚未输入数据的单元格.就这么简单.
就这样.
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.
这篇关于for循环中datagridview中的字符串为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!