自我介绍
我是51CTO新人,初来学习,喜欢研究计算机,学习dotnet的winform,望各位前辈老师们多多指教。
技术分享
今天带来的是在winform中,利用DataTable与DataGridView配合进行数据的显示。
'全局设置
Dim DGVDT As DataTable
'Load等初始化设置
DGVDT = New DataTable
With DGVDT.Columns
.Add("数据1", GetType(String))
.Add("数据2", GetType(String))
End With
DataGridView1.DataSource = DGVDT
'使用方法
AddOneGrid(DataGridView1, DGVDT, CheckedListBox1.SelectedItem, ListBox1.SelectedItem)
DeleteGrid(DataGridView1, DGVDT)
'实现方法
''' <summary>
''' 向数据表中新增一行
''' </summary>
''' <param name="vDGV">用于显示数据的DataGridView</param>
''' <param name="vDT">用于存储数据的DataTable</param>
''' <param name="vData0">新增行的第一列数据</param>
''' <param name="vData1">新增行的第二列数据</param>
''' <returns>返回一个布尔值,True表示顺利执行,False表示执行过程产生了错误。</returns>
''' <remarks>此方法适用于DataGridView的数据源绑定了DataTable的情况,数据参数应该随DataTable的变化而变化</remarks>
Private Function AddOneGrid(vDGV As DataGridView, vDT As DataTable, vData0 As Object, vData1 As Object) As Boolean
Dim result As Boolean = True
Try
If Len(vData0.ToString) > 0 AndAlso Len(vData1.ToString) > 0 Then
Dim dtrow As DataRow = vDT.NewRow
With dtrow
.Item("数据1") = vData0
.Item("数据2") = vData1
End With
vDT.Rows.Add(dtrow)
vDGV.MultiSelect = False
vDGV.Rows(vDGV.Rows.Count - 1).Selected = True
vDGV.CurrentCell = vDGV.Rows(vDGV.Rows.Count - 1).Cells(0)
vDGV.MultiSelect = True
Else
result = False
End If
Catch ex As Exception
result = False
End Try
Return result
End Function
''' <summary>
''' 删除数据表中选中的行
''' </summary>
''' <param name="vDGV">用于显示数据的DataGridView</param>
''' <param name="vDT">用于存储数据的DataTable</param>
''' <returns>返回一个布尔值,True表示顺利执行,False表示执行过程产生了错误。</returns>
''' <remarks>此方法适用于DataGridView的数据源绑定了DataTable的情况</remarks>
Private Function DeleteGrid(vDGV As DataGridView, vDT As DataTable) As Boolean
Dim result As Boolean = True
Try
Dim j As Integer = vDGV.SelectedRows.Count
Do While j > 0
Dim i As Integer = 0
Do
If vDGV.Rows(i).Selected Then
vDT.Rows(i).Delete()
j -= 1
Exit Do
Else
i += 1
End If
Loop
Loop
If vDGV.Rows.Count > 0 Then
vDGV.MultiSelect = False
vDGV.Rows(vDGV.Rows.Count - 1).Selected = True
vDGV.CurrentCell = vDGV.Rows(vDGV.Rows.Count - 1).Cells(0)
vDGV.MultiSelect = True
End If
Catch ex As Exception
result = False
End Try
Return result
End Function
结束语
这个代码片段是我学习的时候用的,由于技术和经验有限,如果哪儿不合适的恳请各位前辈和大佬批评指正。
标签:第三篇,End,51CTO,博文,vDGV,DataGridView,Rows,True,DataTable From: https://blog.51cto.com/u_16253833/7716397