Uploading Datagridview data to MySQL DB - mysql

i created a simple mass upload of data from CSV to datagridview and save all datagridview rows into my MySQL table, the code works perfectly but when i check my database it insert a null values to my table heres my code.
This is my Button for Adding all values from my Datagridview
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd As MySqlCommand
connection.Open()
Dim i As Integer
For i = 0 To DataGridView1.Rows.Count - 2
Dim row As DataGridViewRow = DataGridView1.Rows(i)
cmd = New MySqlCommand("INSERT INTO tbl_handling(tbl_docnumber,tbl_bpref,tbl_cname) values (#docnumber,#bref,#cname)", connection)
cmd.Parameters.Add("#docnumber", MySqlDbType.Int64).Value = DataGridView1.Rows(i).Cells(0).Value.ToString
cmd.Parameters.Add("#bref", MySqlDbType.VarChar).Value = DataGridView1.Rows(i).Cells(1).Value.ToString
cmd.Parameters.Add("#cname", MySqlDbType.VarChar).Value = DataGridView1.Rows(i).Cells(2).Value.ToString
cmd.ExecuteNonQuery()
Next
connection.Close()
connection.Dispose()
MessageBox.Show("Data All Uploaded")
End Sub
This is my code on inserting CSV file to my Datagrid view
Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectData.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "D:\TestFile"
OpenFileDialog1.Filter = "CSV files(*.csv)|*.csv"
OpenFileDialog1.RestoreDirectory = True
Dim colespected As Integer = 5
Dim sline As String = ""
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
Dim thereader As New StreamReader(fName, Encoding.Default)
Do
sline = thereader.ReadLine
If sline Is Nothing Then Exit Do
Dim words() As String = sline.Split(",")
DataGridView1.Rows.Add("")
For ix As Integer = 0 To 2
DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(ix).Value = words(ix)
Next
Loop
thereader.Close()
End If
End Sub

I am assuming that your data is displaying successfully in the grid. So I am only addressing the Button event.
Both commands and connections need to be closed and disposed. Using...End Using blocks do this for you. (BTW Stream objects should be in Using blocks also.) Database objects should be local to the method where they are used. If you .Dispose a connection how do you expect to .Open it later? The command and parameters collection are only created once outside the loop. Just the .Value changes inside the loop.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using connection As New MySqlConnection(ConStr),
cmd As New MySqlCommand("INSERT INTO tbl_handling(tbl_docnumber,tbl_bpref,tbl_cname) values (#docnumber,#bref,#cname)", connection)
cmd.Parameters.Add("#docnumber", MySqlDbType.Int64)
cmd.Parameters.Add("#bref", MySqlDbType.VarChar)
cmd.Parameters.Add("#cname", MySqlDbType.VarChar)
connection.Open()
For i = 0 To DataGridView1.Rows.Count - 2
cmd.Parameters("#docnumber").Value = CLng(DataGridView1.Rows(i).Cells(0).Value)
cmd.Parameters("#bref").Value = DataGridView1.Rows(i).Cells(1).Value.ToString
cmd.Parameters("#cname").Value = DataGridView1.Rows(i).Cells(2).Value.ToString
cmd.ExecuteNonQuery()
Next
End Using
MessageBox.Show("Data All Uploaded")
End Sub
I am a bit worried that tbl_docnumber is an auto-number (identity) primary key in the database. If this is so, then this field should be omitted from the Insert.
This operation would be easier if you filled a DataTable instead of a DataGridView. You could then use a DataAdapter to update the database.

Related

VB.Net from table(time data type) to label

I have a problem regarding producing report but before that I need to run a code in order for me to create multiple conditions for the next report.
I have here a screenshot of my tbldtr. What I want is the value of am_time_in which has the data type of time will be transferred into a label/textbox/variable. I am using Visual Basic with MySQL.
Here is my code
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
checktime()
End Sub
Private Sub checktime()
Dim cn As New MySqlConnection(CnPath)
Dim Sql As String = "SELECT `tbldtr`.`am_time_in` FROM `tbldtr` WHERE `tbldtr`.`id` = '11' AND `tbldtr`.`dtrdate` = '2017-10-16'"
Dim daCmd5 As New MySqlCommand(Sql, cn)
cn.Open()
Dim datinfo As MySqlDataReader = daCmd5.ExecuteReader()
While datinfo.Read()
If IsDBNull(datinfo(0)) = True Then
lblamtimein.Text = ""
Else
lblamtimein.Text = datinfo(0)
End If
End While
cn.Close()
End Sub
End Class
Error here:
The error is occurring on this line -
lblamtimein.Text = datinfo(0)
A timespan needs to be explicitly converted to a string like this -
lblamtimein.Text = datinfo(0).ToString

Adding a record in Datagridview Row in Vb.net

Hello I have Datagridview in my vb.net form and i want to display the data from the MySQL table to the Datagridview (Dgv) of Vb.net but the problem is when i update or delete an record in Dgv the current record that i fetch is adding more display of the current record. I write this code like this because I'm going to add more function on it, I know i can do this using MySqlDataAdapter and DataSet then fill the datagridview of this code but i use this to add more function, for now how can i update/delete an record without adding more rows that i currently fetch. or doubling the row's
Dim SQL as String = "Select * from employee"
Dim cmd as MySqlCommand = new MySqlCommad(SQL, connection)
Dim reader as MysqlDataReader = cmd.executeReader()
Dim empId, empName, empAddress as String
with reader.Read
empId = reader("empId")
empName = reader("name")
empAddress = reader("address")
Dim row() As String
row = new String() {empId, empName, empAddress}
DataGridView1.Rows.Add(row)
End While
reader.close()
cmd.close()
I know the problem is in Rows.Add
Added:
Currently the function of this is to display the data and when event or button was click this Sub will be called again. with out adding more display.
Dim SQL as String = "Select * from employee"
Dim cmd as MySqlCommand = new MySqlCommad(SQL, connection)
Dim reader as MysqlDataReader = cmd.executeReader()
Dim empId, empName, empAddress as String
'before adding new row in datagridview add this code
DataGridView1.Rows.clear();
with reader.Read
empId = reader("empId")
empName = reader("name")
empAddress = reader("address")
so that it will remove the old value of the row and then add the new value in the database
This should do what you want. You can easily select from sql server to datagridview, change data, and pass change from datagridview to sql server.
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source='your_server';Initial Catalog='your_database';Trusted_Connection=True;"
connection = New SqlConnection(connetionString)
sql = "Select * from Product"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Update mysql table in vb.net using datagridview

Hi guys I need help in updating the data on my datagridview. The Scenario is when I click the Search button it will query the appropriate data and display that I want to the datagridview. Then I want to update if their any changes or deleted data from datagridview then also update to my mysql table for new data or record whenever I click the Update Button. The problem is that when I click my search button the messagebox appears "The table contains no changes to save." this means there is no changes but i already change values in datagridview. Anyone could help me?
Here is for my search button code:
Public Class Form1
Dim con As New MySqlConnection
Dim result As Integer
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim ds As New DataSet
Dim dr As MySqlDataReader
Dim sql As String
Dim dt As New DataTable
Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearch.Click
Dim conn As New MySqlConnection
conn.ConnectionString = ("server=127.0.0.1;user id=root;password=12345;database=dbsis3bkenth;")
Try
conn.Open()
sql = "SELECT LName,FName,MI FROM tblsisterbrother where IDNoBrodSis = '" & cbIDNo.Text & "'"
cmd = New MySqlCommand(sql, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows = True Then
MessageBox.Show("Record Found.!")
Else
MessageBox.Show("Record Unfound.!")
End If
dr.Close()
Catch ex As MySqlException
MessageBox.Show("Error in searching to database:error is:" & ex.Message)
Exit Sub
End Try
dr.Close()
RemoveHandler DataGridView1.CellValidating, AddressOf DataGridView1_CellValidating
da.SelectCommand = cmd
da.Fill(ds, "tblsisterbrother")
DataGridView1.DataSource = ds.Tables(0)
conn.Dispose()
conn.Close()
End Sub
Here is the code for my update button:
Private Sub cmdUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
DataGridView1.EndEdit()
Dim dt As DataTable
dt = TryCast(DataGridView1.DataSource, DataTable)
If dt.GetChanges() Is Nothing Then
MessageBox.Show("The table contains no changes to save.")
Else
Dim builder = New MySqlCommandBuilder(da)
Dim rowsAffected As Integer = da.Update(dt)
If rowsAffected = 0 Then
MessageBox.Show("No rows were affected by the save operation.")
Else
MessageBox.Show(rowsAffected & " rows were affected by the save operation.")
End If
End If
End Sub
End Class
Please help me guys to solve my problem :)
According to the MSDN page about GetChanges:
Gets a copy of the DataTable that contains all changes made to it since it was loaded or AcceptChanges was last called.
Since you're declaring the DataTable and loading it only one time, it's working as expected.
To make it work like you want you'll have to use the CellEditEnd event, and call the GetChanges() method from DataGrid.DataSource, something like this:
Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
Dim Changes As DataTable
Changes = TryCast(DataGridView1.DataSource, DataTable).GetChanges()
End Sub

Unsure of how to handle a NullReferenceException

When my form for creating a group of students loads up, I receive a NullReferenceException for seemingly no reason. This is the code that handles the form loading:
Private Sub AddGroupForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To Form1.lstStudents.Items.Count - 1
lstStudentList.Items.Add(Form1.lstStudents.Items.Item(i))
Next
tempStudentList.AddRange(Form1.mainStudentList)
btnAllOut.Enabled = False
btnOneOut.Enabled = False
End Sub
The mainStudentList referred to is a list that is populated upon loading by using MySQL:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim conn As New MySqlConnection("server=localhost;user=root;database=new_project;port=3306;password=********;")
conn.Open()
Dim command As New MySqlCommand("SELECT * FROM students WHERE deleted=0 ORDER BY lastName;", conn)
Dim dataSet As New DataSet()
Dim dataAdapter As New MySqlDataAdapter()
dataAdapter.SelectCommand = command
dataAdapter.Fill(dataSet, "students")
Dim dataTable As DataTable = dataSet.Tables("students")
For Each row As DataRow In dataTable.Rows
Dim newStudent As New Student
newStudent.intIDNum = row.Item("passCode")
newStudent.strFirstName = row.Item("firstName")
newStudent.strLastName = row.Item("lastName")
newStudent.chrGender = row.Item("gender")
newStudent.dateDOB = row.Item("dateOfBirth")
newStudent.intAge = CInt(Today.Year - newStudent.dateDOB.Year)
newStudent.intYearGroup = row.Item("yearGroup")
newStudent.intSkillLevel = SByte.Parse(row.Item("skillLevel"))
mainStudentList.Add(newStudent)
lstStudents.Items.Add(newStudent.nameConcat(newStudent.strFirstName, newStudent.strLastName))
Next
conn.Close()
Catch ex As Exception
MsgBox("Error: " & ex.ToString())
End Try
End Sub
The specific exception occurs when the tempStudentList attempts to load the values in the mainStudentList. Specifically, it states that "Object reference not set to instance of an Object".
Make sure mainStudentList has been initialized first.
c#
List<Student> mainStudentList = new List<Student>();
VB.Net
Dim mainStudentList As New List(Of Student)()

How to display data in datagrid from mysql in multiple forms?

I have 2 forms, in the first form the datagrid populates with data in mysql. Then to repeat this for my second form I copied the code over and changed all variable names, but when I load the form the datagrid is not populated with mysql data, it doesn't even throw an error. Here is the code I used for my first form and below is for my second form.
This is the code for the second form, where it doesn't work, the code is exactly the same (changed variable names) for the first form.
Second form:
Public Class frmShareholderDetails
Dim connection As New MySqlConnection
Dim myadapter As New MySqlDataAdapter
Dim mycommandbuilder As MySqlCommandBuilder
Dim mycommand As MySqlCommand
Dim datatable As New DataTable
Dim dataset As New DataSet
Dim mydatagridviewprinter As datagridviewprinter
Dim objconnection As New MySqlConnection("Server=localhost;database=ba-solutions;user id=root;password=")
'declaring variables
Private Sub frmShareholderDetails_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
connection.ConnectionString =
("Server=localhost;database=ba-solutions;user id=root;password=")
Try
connection.Open()
'opens connection
Catch ex As Exception
MsgBox("Cannot connect to BA-Solutions Database")
End Try
myadapter.SelectCommand = New MySqlCommand
myadapter.SelectCommand.Connection = connection
myadapter.SelectCommand.CommandText = "select * from Shareholder_Details"
'creates adapters
mycommandbuilder = New MySqlCommandBuilder(myadapter)
myadapter.Fill(datatable)
myadapter.SelectCommand.CommandType = CommandType.Text
dataset = New DataSet
myadapter.Fill(dataset, "Shareholder_Details")
rowposition = 0
DGVShareholder.DataSource = dataset.Tables("Shareholder_Details")
'sets datasource
connection.Close()
'close connection
Dim recordsondisplay As Integer
recordsondisplay = DGVShareholder.RowCount
lblRecords.Text = recordsondisplay & " records in database."
End Sub
End Class
Can anyone see where the problem lies? I have been using trial and error, but no solution yet.