vb.net DataGridView把逗号分隔的多个字符串分别赋值到指定几个索引列单元格中,每行代码带注释
时间: 2024-03-23 07:41:17 浏览: 15
假设有一个逗号分隔的字符串,例如"John,Doe,25,Programmer",我们需要将其分别赋值到一个 DataGridView 的不同列中。
首先,我们需要使用 Split 方法将字符串分割成一个字符串数组:
```
Dim values As String() = "John,Doe,25,Programmer".Split(","c)
```
接下来,我们可以将数组中的每个元素分别赋值到 DataGridView 的不同列中:
```
'假设我们有一个名为 myDataGridView 的 DataGridView
myDataGridView.Rows.Add() '添加新行
'分别将数组中的元素赋值给不同的列
myDataGridView.Rows(myDataGridView.Rows.Count - 1).Cells("FirstName").Value = values(0)
myDataGridView.Rows(myDataGridView.Rows.Count - 1).Cells("LastName").Value = values(1)
myDataGridView.Rows(myDataGridView.Rows.Count - 1).Cells("Age").Value = values(2)
myDataGridView.Rows(myDataGridView.Rows.Count - 1).Cells("Profession").Value = values(3)
```
在这个例子中,我们假设 DataGridView 中有四个列分别为 "FirstName"、"LastName"、"Age" 和 "Profession"。我们使用 `Rows.Add()` 方法添加一个新行,然后将数组中的每个元素分别赋值给不同的列。注意,在使用 `Rows` 集合访问行时,我们使用 `Count` 属性减去 1 来获取最后一行的索引。
完整的代码示例如下:
```
Dim values As String() = "John,Doe,25,Programmer".Split(","c)
'假设我们有一个名为 myDataGridView 的 DataGridView
myDataGridView.Rows.Add() '添加新行
'分别将数组中的元素赋值给不同的列
myDataGridView.Rows(myDataGridView.Rows.Count - 1).Cells("FirstName").Value = values(0)
myDataGridView.Rows(myDataGridView.Rows.Count - 1).Cells("LastName").Value = values(1)
myDataGridView.Rows(myDataGridView.Rows.Count - 1).Cells("Age").Value = values(2)
myDataGridView.Rows(myDataGridView.Rows.Count - 1).Cells("Profession").Value = values(3)
```