Reputation: 1520
I'm working on some project which involves many forms .. in each form i have to import an excel into datagrid using below code .. i dont want to duplicate the code for each form .. planning to create module so that i can call the function from each form to import the excel data into datagrid .
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
is there any way to do this ?.
any suggestion appreciated :)
Upvotes: 0
Views: 411
Reputation: 1539
I would create a function like yparask does, but then pass the datagrid
Public Function GetExcelTable(Dgv as datagridview) AS boolean
' do your openfile and import stuff here
return true ' succesfull
return false ' unsuccesfull
Upvotes: 0
Reputation: 34846
Here is a tutorial on Standard Modules in VB .NET.
This will allow you to create your Excel logic in one place and have it be called from multiple forms.
Upvotes: 0
Reputation: 18411
You may have a function:
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
and then call it as:
Me.DataGridView1.DataSource = GetExcelTable()
Upvotes: 1
Reputation: 490
It looks like a pattern you can put into a sub or function and make that call each time you need to call an import:
Public Sub ImportForm()
'Import Logic
End Sub
Then call ImportForm()
everywhere you need it.
Upvotes: 0