提问人:Marco Giglio 提问时间:9/8/2023 最后编辑:djvMarco Giglio 更新时间:9/13/2023 访问量:46
VB.NET 和 DataGridView:如何读取特定的 Cell 值
VB.NET and DataGridView: how read a specific Cell value
问:
我有一个 3 列和 3 行的 DataGridView(这只是一个示例)。我只想读取特定单元格的值(在本例中为 2x2)。你是怎么做到的?我尝试了这段代码,但 visual studio 给我写了一个错误:
“mscorlib.dll 中发生'System.ArgumentOutOfRangeException'类型的未处理异常
附加信息:
Index non compreso nell'intervallo.Richiesto valore non negativo e minore della dimensione della raccolta.”
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'read array and send to DataGridView
Dim cella(3, 3) As String
cella(0, 0) = "Papa"
cella(0, 1) = "Mamma"
cella(0, 2) = "Bimbo1"
cella(0, 3) = "Bimbo2"
cella(1, 0) = "Bianco"
cella(1, 1) = "Rosso"
cella(1, 2) = "Nero"
cella(1, 3) = "Blu"
cella(2, 0) = "Firenze"
cella(2, 1) = "Pisa"
cella(2, 2) = "Livorno"
cella(2, 3) = "Empoli"
cella(3, 0) = "Gatto"
cella(3, 1) = "Cane"
cella(3, 2) = "Panda"
cella(3, 3) = "Macaco"
For x As Integer = 0 To 3
DataGridView1.Columns.Add("newColumnName", "Testo")
Next
For y As Integer = 0 To cella.GetUpperBound(0)
DataGridView1.Rows.Add(cella(0, y), cella(1, y), cella(2, y), cella(3, y))
Next
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Create MsgBox with the value of the specified cell
MsgBox(DataGridView1.SelectedRows.Item(2).Cells(2).Value.ToString())
End Sub
答:
1赞
djv
9/9/2023
#1
不要将数据存储在 UI 中。UI 用于显示和交互,而不是用于存储状态。
创建一个类来表示您的数据
Private Class Datum
Public Sub New(name As String, color As String, city As String, animal As String)
Me.Name = name
Me.Color = color
Me.City = city
Me.Animal = animal
End Sub
Public Property Name As String
Public Property Color As String
Public Property City As String
Public Property Animal As String
End Class
然后,使用类的实例填充列表,并将数据绑定到 DataGridView
Private data As List(Of Datum)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
data = New List(Of Datum) From
{
New Datum("Papa", "Bianco", "Firenze", "Gatto"),
New Datum("Mamma", "Rosso", "Pisa", "Cane"),
New Datum("Bimbo1", "Nero", "Livorno", "Panda"),
New Datum("Bimbo2", "Blu", "Empoli", "Macaco")
}
DataGridView1.DataSource = data
End Sub
最后使用一些逻辑找到您要查找的项目
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim city = data?.Single(Function(d) d.Name = "Bimbo1").City
MessageBox.Show(city)
End Sub
现在,您的数据已脱离 UI,您可以使用逻辑名称访问它、传递数据、查询数据等。
0赞
Heinz Z.
9/13/2023
#2
发生异常的原因是您没有 SelectedRows。如果您只想要一个固定单元,请尝试以下方法:Row
SelectedRows
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Create MsgBox with the value of the specified cell
MsgBox(DataGridView1.Rows.Item(2).Cells(2).Value.ToString())
End Sub
评论