Unsure of how to handle a NullReferenceException - mysql

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)()

Related

Uploading Datagridview data to MySQL DB

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.

Visual Basic connect database with ODBC setting with register

I have the code written to connect to the ODBC registry.
The database name is written to the combobox.
I need to transfer my ip address and password from ODBC.ini to the connect string after selecting the database from the combobox.
This is a connection to MYSQL.
Thank you
Private Sub DsnLookup()
Dim dsnNames As New List(Of String)
Dim reg As Microsoft.Win32.RegistryKey = Registry.CurrentUser.OpenSubKey("Software")
If reg IsNot Nothing Then
reg = reg.OpenSubKey("ODBC")
If reg IsNot Nothing Then
reg = reg.OpenSubKey("ODBC.INI")
If reg IsNot Nothing Then
For Each dsn As String In reg.GetSubKeyNames
dsnNames.Add(dsn)
Next
End If
End If
End If
For Each Name As String In dsnNames
ComboBox1.Items.Add(Name)
Next Name
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DsnLookup()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connString As String = "Database='combobox data;Data Source='ip adres odbc;" _
& "User Id=root;Password=' odbc PWD"
You can get the Server Name (or IP) and Database name from the ODBC.INI but it doesn't store the password. Either include a master password in your connectionstring (securely of course) or look into other authentication options.
This is how to get the Database and Server info from the registry. Keeping your code the same, but replacing the Button1.Click event and adding an additional function:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex >= 0 Then 'Make sure something from dropdown selected
Dim connString As String = String.Format("Database='{0}';Data Source='{1}';User Id=root;", GetODBCValue(ComboBox1.SelectedItem, "Database"), GetODBCValue(ComboBox1.SelectedItem, "Server"))
End If
End Sub
Private Function GetODBCValue(ByVal ODBCName As String, ByVal ValueName As String) As String
Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software")
reg = reg.OpenSubKey("ODBC")
reg = reg.OpenSubKey("ODBC.INI")
reg = reg.OpenSubKey(ODBCName)
Return reg.GetValue(ValueName)
End Function
thank you for the answer
I tried to edit it
Private Function GetODBCValu(ByVal ODBCName As String, ByVal ValueName As String) As String
Dim dsnNames As New List(Of String)
Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software")
reg = reg.OpenSubKey("ODBC")
reg = reg.OpenSubKey("ODBC.INI")
reg = reg.OpenSubKey(ODBCName)
Return reg.GetValue(ValueName)
For Each dsn As String In reg.GetSubKeyNames
dsnNames.Add(dsn)
Next
For Each Name As String In dsnNames
ComboBox1.Items.Add(Name)
Next Name
End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim connString As String = String.Format("Database='{0}';Data Source='{1}';User Id=root;", GetODBCValu(ComboBox1.SelectedItem, "Database"), GetODBCValu(ComboBox1.SelectedItem, "Server"))
Dim conn As New MySqlConnection(connString)
Dim cmd As New MySqlCommand()
Try
Call conecDB()
dt = New DataTable 's_table
Dim con As New SqlConnection
DateTimePicker1.CustomFormat = "yyyy-MM-dd"
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker2.CustomFormat = "yyyy-MM-dd"
DateTimePicker2.Format = DateTimePickerFormat.Custom
conn.Open()
cmd.Connection = conn
da = New MySql.Data.MySqlClient.MySqlDataAdapter("select --- ", connDB)
comBuilderDB = New MySql.Data.MySqlClient.MySqlCommandBuilder(da)
da.Fill(dt)
dbvypis.DataSource = dt
conn.Close()
MessageBox.Show("COMPLET")
Catch ex As MySqlException
Console.WriteLine("Error: " & ex.ToString())
End Try
Try
'declaring variable as integer to store the value of the total rows in the datagridview
Dim max As Integer = dbvypis.Rows.Count - 1
Dim total As String = "TOTAL ----->"
Dim TOTALCOST As Integer = 0
'getting the values of a specific rows
For Each row As DataGridViewRow In dbvypis.Rows
'formula for adding the values in the rows
TOTALCOST += row.Cells(1).Value
Next
dbvypis.Rows(max).Cells(1).Value += TOTALCOST
dbvypis.Rows(max).Cells(0).Value = total
Catch ex As Exception
MsgBox(ex.Message)
End Try
It occurred to me that if I select a database in the comboboxu so it gets into ODBC and connString to the command adds the server and database name
Then it writes to me in the result Index is out of range, Index must be non-negative and must be smaller than the collection size. Parameter name: index

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

How to show data from MySQL in TextBoxes

I need to show a set of data from MySQL like the function of DataGridView or ListView, but using multiple TextBox controls. The result of my work is that all data from a column is together on one TextBox. I don't know how to make a loop.
Code:
Imports System.Data
Imports MySql.Data.MySqlClient
Public Class Form1
Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; database=abc; password=")
Dim query As String = "SELECT id,timein,timeout FROM emp"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Using myCommand As New MySqlCommand("SELECT * FROM emp ORDER BY id ASC", con)
Try
con.Open()
Using myData = myCommand.ExecuteReader()
If myData.HasRows Then
While myData.Read()
Dim idline = String.Format("{0}", myData.GetString(myData.GetOrdinal("id")), Environment.NewLine)
Dim inline = String.Format("{0}", myData.GetString(myData.GetOrdinal("timein")), Environment.NewLine)
Dim outline = String.Format("{0}", myData.GetString(myData.GetOrdinal("timeout")), Environment.NewLine)
idbox1.Text &= idline
idbox2.Text &= idline
idbox3.Text &= idline
timein1.Text &= inline
timein2.Text &= inline
timein3.Text &= inline
timeout1.Text &= inline
timeout2.Text &= inline
timeout3.Text &= inline
End While
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Using
con.Close()
End Sub
End Class
This works fine with me. I got what I need to do. Thank you for the ideas.
"Imports System.Data
Imports MySql.Data.MySqlClient
Public Class Form2
Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; database=abc; password=")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; database=abc; password=")
Dim query As String = "SELECT id,timein,timeout FROM emp"
con.Open()
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM emp ORDER BY id ASC", con)
da.Fill(dt)
idbox1.Text = dt.Rows(0)("id").ToString()
idbox2.Text = dt.Rows(1)("id").ToString()
idbox3.Text = dt.Rows(2)("id").ToString()
timein1.Text = dt.Rows(0)("timein").ToString()
timein2.Text = dt.Rows(1)("timein").ToString()
timein3.Text = dt.Rows(2)("timein").ToString()
timeout1.Text = dt.Rows(0)("timeout").ToString()
timeout2.Text = dt.Rows(1)("timeout").ToString()
timeout3.Text = dt.Rows(2)("timeout").ToString()
con.Close()
End Sub
End Class
"
Have you tried using a DataTable? I built a form that pulls values on load from into a DataTable and in that table you can specify the columns that appear and in what order. I used the built in functions in MS VS17 RC to link the tables. Might help you out with your issue.
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sqlConn As New SqlConnection("Connection String Info")
Dim cmd As New SqlCommand
Dim dr As New SqlDataAdapter("-Query String-", sqlConn)
Dim dt As New DataTable
Try
If sqlConn.State = ConnectionState.Closed Then
sqlConn.Open()
dr.Fill(dt)
Menu.DisplayMember = "prod_name" --add your columns here
Menu.DataSource = dt
sqlConn.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Order.Clear()
For Each Item As Object In Menu.SelectedItems
Order.AppendText(Item.ToString = Environment.NewLine)
Next
End Sub

Mysql DataAdapter Update Method - Doesn't Save Changes

I'm using MySQL in vb.net
Datagridview displayed correctly and everything works properly, the problem arises when I try to update the changes in the database with the update (method)
By default the data is updated in memory "is erased students with ID =" 2 ""
But in the database is not updated, I'm reading the documentation and should work with update
datosAlumnos.Update(ds, "alumnos")
Imports MySql.Data.MySqlClient
Public Class Form1
Dim con As New MySqlConnection
Dim stringCon As String = "server=localhost; user id=root; password=; database=centroeducativo"
Dim listViewAlumnos As New ListBox()
Dim ds As New DataSet()
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Try
con.ConnectionString = stringCon
con.Open()
Dim datosTablas As New MySqlDataAdapter("SHOW TABLES", con)
Dim datosAlumnos As New MySqlDataAdapter("SELECT * FROM alumnos ORDER BY Nombre", con)
Dim datosAsignaturas As New MySqlDataAdapter("SELECT * FROM asignaturas", con)
Dim datosMatriculas As New MySqlDataAdapter("SELECT * FROM matriculas", con)
datosTablas.Fill(ds, "tablas")
datosAlumnos.Fill(ds, "alumnos")
datosAsignaturas.Fill(ds, "asignaturas")
datosMatriculas.Fill(ds, "matriculas")
con.Close()
Dim tabla As DataTable
tabla = ds.Tables("tablas")
Dim fila As DataRow
Me.ListBox1.Items.Clear()
For Each fila In tabla.Rows
Me.ListBox1.Items.Add(fila.Item("Tables_in_centroeducativo"))
Next
Dim filaBorrada As DataRow() = ds.Tables("alumnos").Select("id=2")
filaBorrada(0).Delete()
datosAlumnos.Update(ds, "alumnos")
Catch ex As Exception
End Try
End Sub
Private Sub formularioTabla(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim curItem As String = ListBox1.SelectedItem.ToString()
Select Case curItem
Case "alumnos"
FormularioAlumno()
Case "asignaturas"
FormularioAsignaturas()
Case "matriculas"
FormularioMatriculas()
Case Else
MsgBox("none")
End Select
End Sub
Private Sub FormularioAlumno()
Panel1.Controls.Clear()
Dim dv As DataView = ds.Tables("alumnos").DefaultView
con.Close()
Dim DataGridView As New DataGridView()
Panel1.Controls.Add(DataGridView)
DataGridView.AutoSize = True
DataGridView.DataSource = dv
DataGridView.Columns("id").Visible = False
End Sub
End Class
It seems you forget to set InsertCommand, UpdateCommand and specially Deletecommand.
To make a data adapter update data, it should have those commands. You can set those commands manually or using a MySqlCommandBuilder.
Dim myConn As New MySqlConnection("Connection String")
Dim myDataAdapter As New MySqlDataAdapter()
myDataAdapter.SelectCommand = New MySqlCommand("Select Query", myConn)
Dim myCommandBuilder As MySqlCommandBuilder = New MySqlCommandBuilder(myDataAdapter)