要使用VB的DataGridView控件,你需要做以下步驟:
在窗體上拖放一個DataGridView控件。
在代碼中,定義一個DataTable來存儲數據,并在窗體加載時初始化它。
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' 添加列到DataTable
dt.Columns.Add("ID", GetType(Integer))
dt.Columns.Add("Name", GetType(String))
dt.Columns.Add("Age", GetType(Integer))
' 添加行到DataTable
dt.Rows.Add(1, "Tom", 25)
dt.Rows.Add(2, "John", 30)
dt.Rows.Add(3, "Mary", 28)
' 將DataTable綁定到DataGridView
DataGridView1.DataSource = dt
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' 添加一行數據到DataTable
dt.Rows.Add(4, "Jane", 35)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' 修改DataGridView中選中的行的數據
If DataGridView1.SelectedRows.Count > 0 Then
DataGridView1.SelectedRows(0).Cells("Name").Value = "Updated"
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
' 刪除DataGridView中選中的行
If DataGridView1.SelectedRows.Count > 0 Then
DataGridView1.Rows.Remove(DataGridView1.SelectedRows(0))
End If
End Sub
這樣就可以使用VB的DataGridView控件來顯示和操作數據了。