I was following a tutorial on the internet ( link ) to create a a picture gallery. I got it all working, but i changed:
Private Sub CreateGallery()
i = 0
RemoveControls()
If Directorypath IsNot Nothing Then
Dim di As New IO.DirectoryInfo(Directorypath)
Dim diar1 As IO.FileInfo() = di.GetFiles("*.jpg").Concat(di.GetFiles("*.bmp")).Concat(di.GetFiles("*.png")).Concat(di.GetFiles("*.gif")).ToArray
Dim dra As IO.FileInfo
For Each dra In diar1
DrawPictureBox(dra.FullName, dra.Name)
Next
End If
End Sub
to:
Private Sub CreateGallery()
Dim table = New DataTable
Using Connection = New MySqlConnection("Server=localhost;User Id=root;Password=barra;Database=pap")
Using da = New MySqlDataAdapter("SELECT * FROM filme", Connection)
da.Fill(table)
End Using
End Using
i = 0
RemoveControls()
For Each row As DataRow In table.Rows
Try
Dim bytes() As Byte
bytes = (row("imagem"))
Dim memStream As New MemoryStream(bytes)
DrawPictureBox(memStream, row("titulo"))
Catch ex As Exception
End Try
Next
End Sub
It was working fine, the way i wanted, when i tried to do it on another project it gives me an error on 'MySqlDataAdapter':
Using da = New MySqlDataAdapter("SELECT * FROM filme", Connection)
the erros says : Overload resolution failed because no accessible 'New' can be called with these arguments
I tried almost everything i can't make it work.
convert your function as class and call :
dim new_creator as yourclass
...
Try This
Private Sub CreateGallery()
Dim table As New DataTable
Dim Conn As New SqlConnection
Conn = New SqlConnection("Initial Catalog=<DataBase>;User ID=sa;password=<password>;Data Source=<ServerName>"")
Dim com As String = ""
com = "SELECT * FROM Table "
Dim getComm As New SqlDataAdapter(com, Conn)
getComm.Fill(table)
i = 0
RemoveControls()
For Each row As DataRow In table.Rows
Dim bytes() As Byte
bytes = (row("Imagee"))
Dim memStream As New MemoryStream(bytes)
DrawPictureBox(memStream, row("Bro_Path"))
End Sub
and change ByVal _filename As MemoryStream,
Private Sub DrawPictureBox(ByVal _filename As MemoryStream, ByVal _displayname As String)
Related
I have table with two columns : "Total" and "Returned" I am trying to take all column values from both but it not work with me. It takes only the first row in the column I want total values in the column
My code :
Private Sub TotalTextBox_TextChanged(sender As Object, e As EventArgs) Handles TotalTextBox.TextChanged
Dim str As String = "Server=localhost;Port=3306;Database=testdb;Uid=root;Pwd=password"
Using net As New MySqlConnection(str)
Dim totalnet As String = "Select * from testata where Qty_Returned and Total"
Dim cm As New MySqlCommand(totalnet, net)
net.Open()
Dim rdnet As MySqlDataReader = cm.ExecuteReader()
If rdnet.Read() Then
Label16.Text = rdnet.GetString(12) - rdnet.GetString(11)
Else
End If
End Using
End Sub
Glad you got it working. Just a few suggestions...
Turn on Option Strict for this and all your code.
Comments are inline.
Private Sub testdataDataGridView_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles testataDataGridView.DataBindingComplete
'A Using...End Using block will ensure that your objects that use unmanages
'resources are closed and disposed event if there is an error in the code
Using con As New MySqlConnection("Server=localhost;Port=3306;Database=testdb; Uid=root;Pwd=1234")
'A command object constructor can take an query string and connection as arguments
Using cmd As New MySqlCommand("select sum(Qty_Returned) FROM testdata", con)
'Open the connection at the last possible minute
con.Open()
Dim sqlresult = cmd.ExecuteScalar
Label16.Text = sqlresult.ToString
End Using
Using cmg As New MySqlCommand("select sum(Total) FROM testgdata", con)
Dim sqlresult2 = cmg.ExecuteScalar
Label10.Text = sqlresult2.ToString
End Using
End Using
Label18.Text = (CInt(La
End Sub
Not sure why this code is in this event.
I got the solution with this code:
Private Sub testdataDataGridView_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles testataDataGridView.DataBindingComplete
Dim con As New MySqlConnection("Server=localhost;Port=3306;Database=testdb; Uid=root;Pwd=1234")
Dim cmd As New MySqlCommand
Dim cmg As New MySqlCommand
con.Open()
cmd.Connection = con
cmd.CommandText = "select sum(Qty_Returned) FROM testdata"
Dim sqlresult As Object
sqlresult = cmd.ExecuteScalar
Dim str1 As String
str1 = sqlresult
Label16.Text = str1
cmg.Connection = con
cmg.CommandText = "select sum(Total) FROM testgdata"
Dim sqlresult2 As Object
sqlresult2 = cmg.ExecuteScalar
Dim str2 As String
str2 = sqlresult2
Label10.Text = str2
Label18.Text = Label10.Text - Label16.Text
End Sub
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)
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)()
I need to get all the values of each record in a table, this is so I can then add them to a text file log, a record per line, and then delete them from the database. I'm new to this and have searched how to add SQL query results to an array or a generic list, but I don't fully understand them.
All I have so far is:
Private Sub btnClearAll_Click(sender As Object, e As EventArgs) Handles btnClearAll.Click
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Dim strSQl = "TRUNCATE TABLE CurrentJobs"
Dim commandInsert As New OleDbCommand
commandInsert.CommandText = strSQl
commandInsert.Connection = conn
commandInsert.Connection.Open()
commandInsert.ExecuteNonQuery()
Me.ReportViewer1.RefreshReport()
End Sub
This is for a Uni project, and above is how we have been to shown to do it, however nothing I have found while researching looks similar.
Feel free to use this procedure:
Private Sub DataTableToTextFile()
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Using conn As OleDbConnection = New OleDbConnection(connString)
Dim dt As New DataTable
conn.Open()
'Change the query. It's not a good practice to use '*' in your select queries. Please, use the column names instead.
Dim dataAdapter As New OleDbDataAdapter("SELECT * FROM CurrentJobs", conn)
dataAdapter.Fill(dt)
'Change the path to your desired path
Dim exportPath As String = "C:\Logs\"
Dim exportFileName As String = "log.txt"
'If directory does not exists, create it
If Not Directory.Exists(exportPath) Then
Directory.CreateDirectory(exportPath)
End If
'Write data into the text file
Dim writer As New StreamWriter(exportPath + exportFileName)
Try
Dim sb As New StringBuilder
For Each row As DataRow In dt.Rows
sb = New StringBuilder
For Each col As DataColumn In dt.Columns
sb.Append(row(col.ColumnName))
Next
writer.WriteLine(sb.ToString())
Next
Catch ex As Exception
Throw ex
Finally
If Not writer Is Nothing Then writer.Close()
End Try
'Finally clean database table
Dim strSQl = "Delete From CurrentJobs"
Dim commandDelete As New OleDbCommand(strSQl, conn)
'execute
commandDelete.ExecuteNonQuery()
'close connection
conn.Close()
End Using
End Sub
when i try to select an item in the ListView that has no image in my database this error shows Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'. i tried to put up some code like isDBNull or DBNull but it's applicable.
here's my code:
Private Sub LvPeople_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LvPeople.SelectedIndexChanged
If LvPeople.SelectedItems.Count > 0 Then
Dim connstring As String = "server = localhost; user id = root; database = db; password = root"
Dim Sql As String = "select * from candidate where idn='" & LvPeople.SelectedItems(0).Text & "'"
Dim conn As New MySqlConnection(connstring)
Dim cmd As New MySqlCommand(Sql, conn)
Dim dr As MySqlDataReader = Nothing
conn.Open()
dr = cmd.ExecuteReader()
dr.Read()
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
conn.Close()
End If
End Sub
End Class
the error points here:
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
i really have no idea what to put here. just a newbie here.
Since it is possible that there is no image data previously saved for a row, you need to test for DBNull before trying to use it:
If IsDBNull(dr("photo")) = False Then
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
Else
' maybe display a "no Photo Available" stock image
End If
Note that this DBNull test is different than the one Steve is using. IsDBNull is a language function while the one he is using is a method of the DataReader object, which is also why there are different requirements. Yet a third way would be to compare it to System.DbNull:
If DBNull.Value.Equals(dr("photo")) = False Then
...
End If
Use the DataReader method IsDBNull, but this method requires the position of the field in the IDataRecord used by the reader, so you need to call also GetOrdinal with the name of the field to check
(Links point to the Sql Server version but they are the same for MySql)
Private Sub LvPeople_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LvPeople.SelectedIndexChanged
If LvPeople.SelectedItems.Count > 0 Then
Dim connstring As String = "...."
Dim Sql As String = "select * from candidate where idn=#id"
Using conn = new MySqlConnection(connstring)
Using cmd = new MySqlCommand(Sql, conn)
conn.Open()
cmd.Parameters.AddWithValue("#id", LvPeople.SelectedItems(0).Text)
Using dr = cmd.ExecuteReader()
if dr.Read() Then
if Not dr.IsDbNull(dr.GetOrdinal("photo")) Then
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
End If
End If
End Using
End Using
End Using
End If
End Sub