避免在vb.net中重复编码
我正在做一个涉及多种形式的项目。。在每个表单中,我都必须使用下面的代码将excel导入datagrid。。我不想重复每个表单的代码。。计划创建模块,以便我可以从每个表单调用函数,将excel数据导入datagrid避免在vb.net中重复编码,vb.net,datagridview,Vb.net,Datagridview,我正在做一个涉及多种形式的项目。。在每个表单中,我都必须使用下面的代码将excel导入datagrid。。我不想重复每个表单的代码。。计划创建模块,以便我可以从每个表单调用函数,将excel数据导入datagrid Try With Form1.OpenFileDialog1 .Title = "Please open the STM_Ticket_Template" .Filter = "Excel
Try
With Form1.OpenFileDialog1
.Title = "Please open the STM_Ticket_Template"
.Filter = "Excel Files | *.xlsx"
If .ShowDialog = Windows.Forms.DialogResult.OK Then
Dim fn1 As String = .FileName.ToString
Dim oledbCon As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + fn1 + ";Extended Properties=Excel 12.0;"
conDB = New OleDb.OleDbConnection(oledbCon)
adap = New OleDb.OleDbDataAdapter("Select * From [SAM_TICKETS$]", conDB)
adap.TableMappings.Add("Table", "Excel")
dSet = New DataSet
adap.Fill(dSet)
Me.DataGridView1.DataSource = dSet.Tables(0)
End If
End With
Dim msg As String = MsgBox("Template successfully loaded", MsgBoxStyle.Information, "Creation Template")
Catch ex As Exception
MsgBox("Load Error..." + Environment.NewLine + ex.ToString)
End Try
有没有办法做到这一点
欢迎任何建议:)它看起来像是一种模式,您可以将其放入子模块或函数中,并在每次需要调用导入时进行调用:
Public Sub ImportForm()
'Import Logic
End Sub
然后在任何需要的地方调用ImportForm()。您可能有一个函数:
Imports System.Windows.Forms
Public Function GetExcelTable() AS DataTable
Dim od As OpenFileDialog = new OpenFileDialog
od.ShowDialog
try
With od
.Title = "Please open the STM_Ticket_Template"
.Filter = "Excel Files | *.xlsx"
If .ShowDialog = Windows.Forms.DialogResult.OK Then
Dim fn1 As String = .FileName.ToString
Dim oledbCon As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + fn1 + ";Extended Properties=Excel 12.0;"
conDB = New OleDb.OleDbConnection(oledbCon)
adap = New OleDb.OleDbDataAdapter("Select * From [SAM_TICKETS$]", conDB)
adap.TableMappings.Add("Table", "Excel")
dSet = New DataSet
adap.Fill(dSet)
Return dSet.Tables(0)
End If
End With
Dim msg As String = MsgBox("Template successfully loaded", MsgBoxStyle.Information, "Creation Template")
Catch ex As Exception
MsgBox("Load Error..." + Environment.NewLine + ex.ToString)
End Try
End Function
然后称之为:
Me.DataGridView1.DataSource = GetExcelTable()
这里有一个关于的教程
这将允许您在一个位置创建Excel逻辑,并从多个表单调用它。我会像yparask一样创建一个函数,但随后会传递数据网格
Public Function GetExcelTable(Dgv as datagridview) AS boolean
' do your openfile and import stuff here
return true ' succesfull
return false ' unsuccesfull
把你的代码抽象成一个模块,这样你就可以在表单之间共享公共功能了。是的,你是对的。。我知道这个方法肯定会奏效。对于每一个我需要将excel数据导入不同的datagrid(例如datagridview1、datagridview2等),如何做到这一点上面的代码可能还没有100%准备就绪。您可能需要在函数参数列表中包含oledbCon和其他一些参数。但我想你明白我的意思了。。代码可以完美地工作。我根据需要做了一些改变。谢谢你的时间:)祝你今天愉快