Instead of using existing columns, Datagridview creates F1,F2 columns.(VB.NET) - vb.net

When importing an excel file into a datagridview, the procedure is creating new columns in the datagridview rather than using existing columns.
After importing it is showing like this
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

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

How to fetch a particular column from Ms Access Database in Visual Basic

How do I read a particular column from database..
myConnection.Open()
Dim str As String = "SELECT fullname' FROM STUDENTS"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
ListBox1.DataSource = dt
myConnection.Close()
Instead of getting the actual content of the database, what I get is System.Data.DataRowView
You need to set the DisplayMember property of the ListBox to the name of the column you want displayed. If you don't do that, you will see the result of calling ToString on each item, which is why you are seeing the name of the type of the items. Note that you should set the DisplayMember before setting the DataSource.

Import spread sheet (OpenOffice) to Visual Basic .net combo box

I have a list of client names, project names, employee names, and hourly rates in an OpenOffice spreadsheet that I need to import to Visual Basic .net 2017. It would be preferred if I could do this to a combo box, so the user can just select the names from a drop-down list. It seems as if this is impossible without setting up an SQL server. Does anyone know how I should go about doing this?
I've tried this but it says that it can't connect to Microsoft.Ace.OLEDB.12.0
I got this code from a YouTube video
Private Sub btnGetSpread_Click(sender As Object, e As EventArgs) Handles btnGetSpread.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim dataSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim path As String = "P:\Coding\Visual Studio\Visual Basic\TestProject\TestProject\bin\Files\Company_Sheet.ods"
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Ace.OLEDB.12.0;Data Source =" + "P:\Coding\Visual Studio\Visual Basic\TestProject\TestProject\bin\Files\Company_Sheet.ods" + ";Extended Properties=Excel 12.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
dataSet = New System.Data.DataSet
MyCommand.Fill(dataSet)
dgvSpread.DataSource = dataSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
This will get you started. I sometimes have to import data from Excel spreadsheets into an Oracle database, this code is years old, but still works (VS 2013). Modify to suit your situation.
Dim sourceFile As String = "C:\Users\appdata\Documents\SomeData.xls"
Dim srcConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sourceFile & ";Extended Properties=""Excel 8.0;HDR=YES;"""
Dim srcConn As OleDbConnection = New OleDbConnection(srcConnString)
srcConn.Open()
' in the select statement, the fields are the column names in the spreadsheet and are expected to be in row 1 and are case sensitive
' the from clause in the query is the tab of the spreadsheet where the data is
Dim cmdExcel As OleDbCommand = New OleDbCommand("Select NAME,ADDRESS,CITY,STATE,ZIP From [DATA$] Where some where clause", srcConn)
Dim drExcel As OleDbDataReader = cmdExcel.ExecuteReader()
' Now loop through the rows in the spreadsheet
While drExcel.Read()
'Do stuff ...
End While

How do I filter multiple columns in datagridview exported from excel in VB.NET

I have a datagridview which i import an excel file.my excel columns are name,id,sex,grade,seat no .what i want is filter all the columns (multi column filter) in the datagridview except name and id via a textbox. i.e. when i type a single word in the text box i want it to filter the columns of sex,grade and seat no at the same time.
here is the excel importing code to the datagridview....
Private Sub OpenFileDialog1_FileOk(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim filePath As String = OpenFileDialog1.FileName
Dim extension As String =
Path.GetExtension(filePath)
Dim header As String = If(rbHeaderYes.Checked, "YES", "NO")
Dim conStr As String, sheetName As String
conStr = String.Empty
Select Case extension
Case ".xls"
'Excel 97-03
conStr = String.Format(Excel03ConString, filePath, header)
Exit Select
Case ".xlsx"
'Excel 07
conStr = String.Format(Excel07ConString, filePath, header)
Exit Select
End Select
'Get the name of the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
cmd.Connection = con
con.Open()
Dim dtExcelSchema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
sheetName = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()
con.Close()
End Using
End Using
'Read Data from the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
Using oda As New OleDbDataAdapter()
Dim dt As New DataTable()
cmd.CommandText = (Convert.ToString("SELECT * From [") & sheetName) + "]"
cmd.Connection = con
con.Open()
oda.SelectCommand = cmd
oda.Fill(dt)
con.Close()
'Populate DataGridView.
DataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
You should bind your DataTable to a BindingSource, which you would add in the designer, and then bind that to the grid. You can then filter the data by setting the Filter property of the BindingSource. It's basically a SQL WHERE clause so, just like in SQL, you can use AND and OR operators to combine multiple criteria, e.g.
myBindingSource.Filter = String.Format("Column1 LIKE '%{0}%' OR Column2 LIKE '%{0}%'", myTextBox.Text)
Just note that you can only use LIKE for text columns, not numbers or dates or anything else.

operator/operand type mismatch when update dbf file

i have a program needs to update data in dbf file. but it keeps appear error 'operator/operand type mismatch'. here is sample code :
Dim con As OleDbConnection = New OleDbConnection("Provider=vfpoledb;Data Source=C:\folder\paytran.dbf;Collating Sequence=machine;")
Try
Dim strSQL As String = "UPDATE paytran.dbf SET workhr = 20 WHERE empno = 102"
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
con.Open()
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
' Using DataAdapter object fill data from database into DataSet object
myDA.Fill(myDataSet, "MyTable")
' Binding DataSet to DataGridView
DGV.DataSource = myDataSet.Tables("MyTable").DefaultView
con.Close()
con = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message, "Error Select Data")
Finally
If con IsNot Nothing Then
con.Close()
End If
End Try
please help me..
Its your connection string. The connection string should only have to point to the PATH where the data files are located, then all the SQL based commands will by default be able to see any .DBF tables IN that path (or forward if subpaths exists).
Data Source=C:\folder
instead of
Data Source=C:\folder\paytran.dbf
So, now if you have 30 tables in the "C:\folder", you can now query from ALL of them as needed.
You need to explicitly open and close the DBF. Try:
Dim strSQL As String = "Use paytran in 0 shared;UPDATE paytran SET workhr = 20 WHERE empno = 102;use in select('paytran')"

How to add Items in the DatagridViewComboboxColumn of DatagridView during runtime

I have a datagridview with three columns which is filled using Datareader. There is a DatagridViewComboboxcolumn in the datagridView.
I want this DatagridViewComboboxcolumn should also be filled using datareader.
Please suggest how can i add items to DatagridViewComboboxcolumn using Datareader.
Below is the code that i have tried.
Here dr is SqlDatareader
Datagridview.Rows.Add(dr("Column1").ToString, dr("Column2"),dr("DatagridViewComboboxcolumn "))
But when i add this way im getting error on the DatagridViewComboboxcolumn Column.
Please Suggest
As previously mentioned, you cannot set the DataSource of a DataGridViewColumn to a DataReader (since this is a forward only, database connected object). What you can however do is fill a DataTable and the set the DataSource on the DataGridViewColumn to this DataTable. You will also need to set the DataPropertyName (this is the column name of the DataGridView's datasource), ValueMemeber and DisplayMember. The example below uses the Adventureworks DB and populates a DataGridView with 4 columns (one of which is a combobox -- ProductIdCombo). Simply create a form, drop a DataGridGridView control on it named DataGridView1 and run the following. The ProductId column demonstrates that the underlying column bound to the combo (ProductIdCombo column)is indeed updating the ProductId field in the dtProductsInventory DataTable.
Dim dtProductInventory As New System.Data.DataTable
Dim dtProducts As New System.Data.DataTable
Using objSqlServer As New System.Data.SqlClient.SqlConnection("Server=LOCALHOST\SQLEXPRESS; Integrated Security=SSPI;Initial Catalog=AdventureWorks")
objSqlServer.Open()
Dim sqlCmd As New System.Data.SqlClient.SqlCommand("select * from production.ProductInventory", objSqlServer)
dtProductInventory.Load(sqlCmd.ExecuteReader)
sqlCmd.CommandText = "Select * from production.product"
dtProducts.Load(sqlCmd.ExecuteReader)
End Using
DataGridView1.AutoGenerateColumns = False
DataGridView1.DataSource = dtProductInventory
Dim colProductIdCombo As New System.Windows.Forms.DataGridViewComboBoxColumn()
colProductIdCombo.DataSource = dtProducts
colProductIdCombo.DisplayMember = "Name"
colProductIdCombo.ValueMember = "ProductId"
colProductIdCombo.DataPropertyName = "ProductId"
colProductIdCombo.HeaderText = "ProductIdCombo"
DataGridView1.Columns.Add(colProductIdCombo)
Dim colProductId As New System.Windows.Forms.DataGridViewTextBoxColumn()
colProductId.DataPropertyName = "ProductId"
colProductId.HeaderText = "ProductId"
DataGridView1.Columns.Add(colProductId)
Dim colShelf As New System.Windows.Forms.DataGridViewTextBoxColumn()
colShelf.DataPropertyName = "Shelf"
colShelf.HeaderText = "Shelf"
DataGridView1.Columns.Add(colShelf)
Dim colQuantity As New System.Windows.Forms.DataGridViewTextBoxColumn()
colQuantity.DataPropertyName = "Quantity"
colQuantity.HeaderText = "Quantity"
DataGridView1.Columns.Add(colQuantity)