Home > Net >  Instead of using existing columns, Datagridview creates F1,F2 columns.(VB.NET)
Instead of using existing columns, Datagridview creates F1,F2 columns.(VB.NET)

Time:01-15

When importing an excel file into a datagridview, the procedure is creating new columns in the datagridview rather than using existing columns.

Before Importing

After importing it is showing like this

After Importing

Function ExcelImport() As Boolean
Try
Dim fpath As String
fpath = "C:\Users\rajes\OneDrive\Documents\Visual Studio 2010\Projects\CARA Bank Import\CARA Bank Import\bin\Debug\CARATemplate.xlsx"
Dim MyConnection As OleDb.OleDbConnection
Dim Ds As System.Data.DataSet
Dim MyAdapter As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fpath & ";Extended Properties=""Excel 12.0;HDR=NO;""")

MyAdapter = New System.Data.OleDb.OleDbDataAdapter("Select [F1],[F2], [F3],[F4], [F5],[F6], [F7],[F8] from [Bank$A8:H10]", MyConnection)
Ds = New System.Data.DataSet
MyAdapter.Fill(Ds)


With FrmData.DataGridView1
   .DataSource = Ds.Tables(0)

End With

ExcelImport = True
Catch ex As Exception
MsgBox(ex.Message)
ExcelImport = False
End Try

End Function


i want to import excel data to the existing columns . even tried

frmdata.datagridview1.AutoGenerateColumns = False

CodePudding user response:

You need to set the DataPropertyName of each grid column to the name of the data source property or column you want it to bind to. If your data source columns are named "F1", "F2", etc, then that's what you need to set as the DataPropertyName of the grid columns. If you created those grid columns in the designer, that's where you should set that property.

If you don't want to display every column from the data source then you'll also need to set AutoGenerateColumns to False in code before setting the DataSource, so no extra columns are generated.

  • Related