Well, I have a bunch of .txt files that I'm importing in a DataGridView
with vb.net, these files will always have different columns, just like these two examples:
And I'm using the next code to loop through the rows and columns of the DataGridView and also the code insert the data to a mysql table, now, the process I make, it's the next:
- I open the .txt file.
- I tried to insert the data with the First DataGridView, but with the error, the data it's not supposed to be inserted to the table, nevertheless it does it, and although it only has 4 colummns, when I check my database, it shows everything messed up, and it duplicates columns, like the lower image.
- And then I "export" them to the mysql table. And when I do that, I get the error in the upper image.
Here's my code:
Private Sub ExportarToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExportarToolStripMenuItem.Click Dim conn As MySqlConnection = New MySqlConnection("Server=localhost;user=root;password=1234;database=chafa;port=3306") conn.Open() Dim comm As MySqlCommand = New MySqlCommand() comm.Connection = conn Dim col1, col2, col3, col4, col5, col6, col7, col8, col9, col10 Dim tabla As New DataTable For i = 2 To DgvDatos.Rows.Add - 1 Step 1 For j = 0 To Me.DgvDatos.Columns.Count - 1 col1 = DgvDatos.Rows(i).Cells(j).Value() col2 = DgvDatos.Rows(i).Cells(j).Value() col3 = DgvDatos.Rows(i).Cells(j).Value() col4 = DgvDatos.Rows(i).Cells(j).Value() col5 = DgvDatos.Rows(i).Cells(j).Value() col6 = DgvDatos.Rows(i).Cells(j).Value() col7 = DgvDatos.Rows(i).Cells(j).Value() col8 = DgvDatos.Rows(i).Cells(j).Value() col9 = DgvDatos.Rows(i).Cells(j).Value() col10 = DgvDatos.Rows(i).Cells(j).Value() comm.CommandText = "insert into ejemplo(col1,col2,col3,col4,col5,col6,col7,col8,col9,col10) values('" & col1 &_ "','" & col2 & "','" & col3 & "','" & col4 & "','" & col5 & "','" & col6 & "','" & col7 & "','" & col8 & "','" & col9 & "','" & col10 & "')" comm.ExecuteNonQuery() Next Next MessageBox.Show("Datos Agregados Correctamente") conn.Close() End Sub
What am I doing wrong? Thanks in advance and sorry If I'm asking a repeated question.
MySqlDataAdapter
using aSELECT
command and a connection. Then using aMySqlCommandBuilder
createINSERT
,UPDATE
andDELETE
command automatically. Put data in theDataTable
and if you need to manipulate them, set theDataTable
asDataSource
of theDataGridView
. To save changes, callUpdate
method of table adapter. – Reza Aghaei