简体   繁体   English

VB.net默认datagridview数据

[英]VB.net default datagridview data

So I am have to set some default values in a datagridview, to do so I am using the following code, It is working but I am wondering if I can make the code shorter.所以我必须在 datagridview 中设置一些默认值,为此我使用以下代码,它正在工作,但我想知道是否可以缩短代码。

  Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    WindowState = FormWindowState.Maximized

    'default values for diameterdata
    With DataDiameters
        .Rows.Add(6)
        .Rows(0).Cells(0).Value = "DN20"
        .Rows(0).Cells(1).Value = "21,7"
        .Rows(1).Cells(0).Value = "DN25"
        .Rows(1).Cells(1).Value = "28,5"
        .Rows(2).Cells(0).Value = "DN32"
        .Rows(2).Cells(1).Value = "37,2"
        .Rows(3).Cells(0).Value = "DN40"
        .Rows(3).Cells(1).Value = "43,1"
        .Rows(4).Cells(0).Value = "DN50"
        .Rows(4).Cells(1).Value = "54,4"
        .Rows(5).Cells(0).Value = "DN65"
        .Rows(5).Cells(1).Value = "70,3"
        .Rows(6).Cells(0).Value = "DN80"
        .Rows(6).Cells(1).Value = "82,5"
        .Rows(7).Cells(0).Value = "DN100"
        .Rows(7).Cells(1).Value = "107,1"

    End With


End Sub

Create a single array with all your elements.创建一个包含所有元素的数组。 Then, loop through your DataGridView cells and set the values contained into the array.然后,循环遍历您的 DataGridView 单元格并设置包含在数组中的值。

Dim arrayItems() As String = {"DN20", "21,7", "DN25", "DN32", "37,2", "DN40", ......}
Dim indexArray As Integer = 0

    For i = 0 To 7
        For j = 0 To 1
            DataGridView1.Rows(i).Cells(j).Value = arrayItems(indexArray)
            indexArray += 1
        Next
    Next
  With DataDiameters
        .Rows.Add({"DN20", 21.7})
          etc
    End With

or like this if you want to keep everything as string或者像这样,如果您想将所有内容保留为字符串

        With DataDiameters
            .Rows.Add({"DN20", "21,7"})
              etc
        End With

You will find easier to play with the gridview if you make your grid with actual code like this如果您使用这样的实际代码制作网格,您会发现使用 gridview 会更容易

 Dim arrayColumn(2) As String
        With DataDiameters
            .Columns.Add("DNmaat", "DN maat")
            .Columns.Add("InnerDiameter", "Inner Diameter")
            .Rows.Add({"DN20", 21.7})
            ' arraycolumn(0)="DN20"
            ' arraycolumn(1)="21,7"
            ' or like this .Rows.Add(arrayColumn)
            'This will let you dynamically change everything at runtime

        End With

On the long run, because your grid is not hard coded then you can change everything at runtime.从长远来看,因为您的网格不是硬编码的,所以您可以在运行时更改所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM