首先,您需要将 DataGridView 添加到窗体。然后给它命名,在这个例子中我的是 dgvInvoice。一旦您在表单上获得了控件,您需要将列添加到该 DataGridView。您可以通过单击控件并在右上角单击黑色播放按钮并单击“添加列”或类似的东西来做到这一点。当您在屏幕右侧添加列时,请确保给它们一个设计名称;这是对您的专栏的引用。完成此操作后,您可以开始保存到 XML...
这是一个小示例,可帮助您入门...
首先在您想要的任何地方创建一个空的 XML 文件...文件中不需要只有一个空的 XML 文件。然后按照下面...
Imports System.IO
Imports System.Xml
Imports System.Text
Public filePath As String = "PUT YOUR PATH TO XML HERE" - 'YOUR FILE PATH TO YOUR XML FILE GOES HERE'
Private Sub btnSaveGrid_Click(sender As System.Object, e As System.EventArgs) Handles btnSaveGrid.Click
CompileGrid() 'Using another sub to actually do the saving...
End Sub
***************************************************************************
下一个子......
Private Sub CompileGrid()
'Get the XML from the table!'
Dim dt As New DataTable("invoices") 'YOU CAN ADD WHATEVER NAME YOU WANT HERE'
'THIS WILL ADD YOUR COLUMN NAMES TO THE TABLE'
For i As Integer = 0 To dgvInvoice.ColumnCount - 1
dt.Columns.Add(dgvInvoice.Columns(i).Name, GetType(System.String))
Next
'THIS WILL ADD YOUR ROWS DATA TO THE TABLE'
Dim myrow As DataRow
Dim icols As Integer = dgvInvoice.Columns.Count
For Each drow As DataGridViewRow In Me.dgvInvoice.Rows
myrow = dt.NewRow()
For i As Integer = 0 To icols - 1
myrow(i) = drow.Cells(i).Value
Next
dt.Rows.Add(myrow)
Next
'NEXT LETS WRITE THE DATA TO AN XML FILE'
dt.WriteXml(filePath)
End Sub
现在,如果您在记事本或任何您想使用的文件中打开该文件,您将在该文件中看到您的数据。现在不要修改它,因为你可以在每次这样做时自动覆盖它。