VB.NET 和 DataGridView:如何读取特定的单元格值

问题描述 投票:0回答:1

我有一个 3 列和 3 行的 DataGridView(这只是一个示例)。我只想读取特定单元格的值(在本例中为 2x2)。你怎么做到这一点?我尝试这段代码,但 Visual Studio 写信给我有一个错误:

“mscorlib.dll 中发生了类型为‘System.ArgumentOutOfRangeException’的未处理异常

附加信息:

非压缩索引间隔。 Richiesto valore non negativo e minore dellaDimensione 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
arrays vb.net datagridview basic selectedvalue
1个回答
0
投票

不要将数据存储在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,您可以使用逻辑名称访问它、传递数据、查询数据等。

© www.soinside.com 2019 - 2024. All rights reserved.