SQL Download Image into Picture Box 'Out of Memory' Error - sql

*strong text*Okay, I've got a test application which is just to test the Uploading and Downloading of images to/from an SQL Server. The upload code works, but when I try to retrieve the image from the SQL Server I receive an 'Out of Memory' error. However, when I change the picturebox from .BackGroundImage to just .Image the code works flawlessly.
I require the image to be in the format of a BackGoundImage so that I can easily change the size of the image (center, stretch ect).
The error:
An unhandled exception of type 'System.OutOfMemoryException' occurred
in System.Drawing.dll
Additional information: Out of memory.
The code for retrieving the image from the SQL Server is:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
'Retrieve Image
GroupBox2.BringToFront()
GroupBox2.Visible = True
Label1.Visible = False
TextBox1.Visible = False
con.Open()
Dim cmd As New SqlCommand("SELECT DP FROM PersonsA WHERE Members_ID = 1", con)
cmd.CommandType = CommandType.Text
Dim ImgStream As New IO.MemoryStream(CType(cmd.ExecuteScalar, Byte()))
PictureBox2.BackgroundImage = Image.FromStream(ImgStream, False, True)
ImgStream.Dispose()
con.Close()
End Sub
The error highlights the PictureBox2.BackgroundImage = Image.FromStream(ImgStream, False, True) line.
Additional information:
Only 1 row is expected as Members_ID is Primary Key.
SQL Server is MS SQL Server + Management Studio.
The DP Column is formatted as 'Image' and stores the picture like this:
0xFFD8FFE000104A46494600010201000000000000FF....
Here's the upload image code (WORKING)
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'Upload Image
con.Open()
Dim cmd As New SqlCommand("UPDATE PersonsA SET DP=#DP WHERE Members_ID = 1", con)
Dim ms As New MemoryStream()
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("#DP", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
MessageBox.Show("Image has been saved", "Save", MessageBoxButtons.OK)
Label1.Visible = False
TextBox1.Visible = False
con.Close()
Imports and Dims
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
'path variable use for Get application running path
Dim path As String = (Microsoft.VisualBasic.Left(Application.StartupPath, Len(Application.StartupPath) - 9))
Dim con As New SqlConnection("CONNECTION_STRING;")
Dim cn As New SqlConnection("CONNECTION_STRING;")
Dim cmd As SqlCommand
Any ideas on why I'm receiving the 'Out of Memory Error'? The program is tiny and doesn't seam to be using excessive amounts of RAM so it has to be with my code...
[EDIT 1]
Following Jaques very helpful advice I've changed my code to the following - note there's two errors as read is not declared - what should that be declared as?
Dim cmd As New SqlCommand("SELECT DP FROM PersonsA WHERE Members_ID = 1", con)
cmd.CommandType = CommandType.Text
Dim Buffersize As Integer = 4096
Dim retval As Long = 0
Dim TempLen1 As Long = 0
Dim startindex As Long = 0
Dim reference_temp As [Byte]() = New [Byte](4095) {}
Dim RefTemp As New List(Of Byte)()
Dim Read As
retval = read.GetBytes(0, startindex, reference_temp, 0, buffersize)
'0 is the first Column
TempLen1 += retval
While retval = buffersize
RefTemp.AddRange(reference_temp)
startindex += buffersize
retval = read.GetBytes(0, startindex, reference_temp, 0, buffersize)
TempLen1 += retval
End While
RefTemp.AddRange(reference_temp)
Dim Reference_temp1 As Byte() = RefTemp.GetRange(0, CInt(TempLen1)).ToArray()
End Sub
[EDIT 2]
I'm now receiving an error on the retval - read.GetBytes(16, startindex.... line.
An unhandled exception of type 'System.InvalidOperationException'
occurred in Microsoft.VisualBasic.dll
Additional information: Invalid attempt to read when no data is
present.
My code so far:
'Retrieve Image
GroupBox2.BringToFront()
GroupBox2.Visible = True
Label1.Visible = False
TextBox1.Visible = False
con.Open()
Dim cmd As New SqlCommand("SELECT DP FROM PersonsA WHERE Members_ID = 1", con)
cmd.CommandType = CommandType.Text
Dim read = cmd.ExecuteReader
Dim Buffersize As Integer = 4096
Dim retval As Long = 0
Dim TempLen1 As Long = 0
Dim startindex As Long = 0
Dim reference_temp As [Byte]() = New [Byte](4095) {}
Dim RefTemp As New List(Of Byte)()
retval = read.GetBytes(16, startindex, reference_temp, 16, Buffersize)
'0 is the first Column
TempLen1 += retval
While retval = buffersize
RefTemp.AddRange(reference_temp)
startindex += buffersize
retval = read.GetBytes(16, startindex, reference_temp, 16, Buffersize)
TempLen1 += retval
End While
RefTemp.AddRange(reference_temp)
Dim Reference_temp1 As Byte() = RefTemp.GetRange(16, CInt(TempLen1)).ToArray()
Dim ImgStream As New IO.MemoryStream(Reference_temp1)
PictureBox2.BackgroundImage = Image.FromStream(ImgStream, False, True)
ImgStream.Dispose()

Why don't you use the GetBytes from a DataReader like (Its C#, but I'm sure you can convert it :))
'Retrieve Image
GroupBox2.BringToFront()
GroupBox2.Visible = True
Label1.Visible = False
TextBox1.Visible = False
con.Open()
Dim cmd As New SqlCommand("SELECT DP FROM PersonsA WHERE Members_ID = 1", con)
cmd.CommandType = CommandType.Text
Dim read = cmd.ExecuteReader();
if(read.HadRows) then
read.Read() 'Reads the first record from the DataReader
Convert this to VB:
int buffersize = 4096;
long retval = 0;
long TempLen1 = 0;
long startindex = 0;
Byte[] reference_temp = new Byte[4096];
List<byte> RefTemp = new List<byte>();
retval = read.GetBytes(0, startindex, reference_temp, 0, buffersize); //0 is the first Column
TempLen1 += retval;
while (retval == buffersize)
{
RefTemp.AddRange(reference_temp);
startindex += buffersize;
retval = read.GetBytes(0, startindex, reference_temp, 0, buffersize);
TempLen1 += retval;
}
RefTemp.AddRange(reference_temp);
byte[] Reference_temp1 = RefTemp.GetRange(0, (int)TempLen1).ToArray();
Then add your code
Dim ImgStream As New IO.MemoryStream(Reference_temp1)
PictureBox2.BackgroundImage = Image.FromStream(ImgStream, False, True)
ImgStream.Dispose()
EndIf

I'd like to thank Jaques for his/her efforts in helping me. The solution was a little simpler than that answer - which still resulted in a 'Out of Memory' Error. But the efforts made are extremely appreciated. In the end this code worked without any errors.
'Retrieve Image
GroupBox2.BringToFront()
GroupBox2.Visible = True
Label1.Visible = False
TextBox1.Visible = False
Dim stream As New MemoryStream()
con.Open()
Dim cmd As New SqlCommand("SELECT DP FROM PersonsA WHERE Members_ID = 1", con)
cmd.CommandType = CommandType.Text
Dim image As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
Stream.Write(image, 0, image.Length)
con.Close()
Dim bitmap As New Bitmap(stream)
PictureBox2.BackgroundImage = bitmap
PictureBox2.BackgroundImageLayout = ImageLayout.Stretch

Related

cannot retrive image from sql server to vb .net form

I am trying to display user with image using id; it throws an exception
Conversion from type 'Byte()' to type 'Byte' is not valid.
When I remove image code; its working fine displaying other data.
If rdbtninvestigator.Checked = True Then
Dim mycmd1 As New SqlCommand("Select * From investigator where id=#id ", connection)
mycmd1.Parameters.Add("#id", SqlDbType.VarChar).Value = txtid1.Text
Dim table As New DataTable
Dim adapter As New SqlDataAdapter(mycmd1)
adapter.Fill(table)
If table.Rows.Count > 0 Then
lblid.Text = table.Rows(0)(0).ToString()
lblname.Text = table.Rows(0)(1).ToString()
lblusername.Text = table.Rows(0)(2).ToString()
txtpassword.Text = table.Rows(0)(3).ToString()
Dim img As Byte
img = table.Rows(0)(4)
Dim ms As New MemoryStream(img)
picuser.Image = Image.FromStream(ms)
btnupdate.Enabled = True
btndelete.Enabled = True
Else
MsgBox("Account does not exist")
btnupdate.Enabled = False
btndelete.Enabled = False
End If
Images stored in databases are stored as a byte array. The error message you're getting say you are attempting to store the image in a byte variable, not a byte array.
The line of code you need to add/correct is:
Dim image As Byte()
That line creates a variable of type Byte(), a byte array.

asp.net vb Button.click insert to sql working at client but not working when move to server

This code is working a PC. I have filled grid view with the dataset, so I suppose I can read Excel.
However, the insert to sql part is not working when I copy the code to the server and I don't know why. It is not throwing any errors.
I removed the try catch lines but still, there are no errors.
I am adding new code block, I did a test and wrote a siple insert code like;
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim mysql_connection As New SqlConnection
mysql_connection.ConnectionString = "Data Source=SRV01;Initial Catalog=TR_Development;Persist Security Info=True;User ID=sa"
Dim command As String = "insert into gez_test (test) values ('c')"
Dim mysqlcommand As New SqlCommand
mysqlcommand.CommandType = CommandType.Text
mysqlcommand.CommandText = command
mysqlcommand.Connection = mysql_connection
If mysql_connection.State = ConnectionState.Closed Then mysql_connection.Open()
mysqlcommand.ExecuteNonQuery()
If mysql_connection.State = ConnectionState.Open Then mysql_connection.Close()
End Sub
And at server it is not inserting. What can be the problem any idea?
Orginal code
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim path_ As String = "\\exchange\COMPANY\web\" + FileUpload1.FileName
FileUpload1.PostedFile.SaveAs(path_)
Dim identifier As Boolean = False
Dim connStr As String = "provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + path_ + "';Extended Properties=Excel 12.0;"
Dim MyConnection As OleDbConnection
Dim ds As DataSet
Dim MyCommand As OleDbDataAdapter
MyConnection = New OleDbConnection(connStr)
MyConnection.Open()
Dim dtSheets As DataTable = MyConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
If sheet = "'BAS+Surcharges$'" Then
identifier = True
Exit For
End If
Next
If identifier = True Then
MyCommand = New OleDbDataAdapter("select * from [BAS+Surcharges$]", MyConnection)
ds = New System.Data.DataSet()
MyCommand.Fill(ds)
MyConnection.Close()
'**************SQL***************
Dim line, columns As Integer
line = ds.Tables(0).Rows.Count
columns = ds.Tables(0).Columns.Count
Label1.Text = line.ToString
ASPxTextBox1.Text = line.ToString
If line > 0 And columns = 16 Then
Dim command As String = "exec SP_INTRA_EXCEL_LINE_INSERT" _
+ " #line_isim, #nereden, #via, #nereye, #transit_sure, #baslangic_tarihi," _
+ "#e_kadar_gecerli, #kalem_kodu, #fiyatlandirma, #20DRY, #40DRY, #40HDRY," _
+ "#40HREF_NOR, #kayit_eden"
Dim mysql_connection As New SqlConnection
mysql_connection.ConnectionString = ConfigurationManager.ConnectionStrings("TR_DevelopmentConnectionString").ConnectionString
Dim mysqlcommand As New SqlCommand
mysqlcommand.CommandType = CommandType.Text
mysqlcommand.CommandText = command
mysqlcommand.Connection = mysql_connection
Dim line_isim, nereden, via, nereye, transit_sure, baslangic_tarihi, e_kadar_gecerli,
kalem_kodu, fiyatlandirma, _20DRY, _40DRY, _40HDRY,
_40HREF_NOR, kayit_eden As String
If mysql_connection.State = ConnectionState.Closed Then mysql_connection.Open()
For i = 6 To line - 1
line_isim = ds.Tables(0).Rows(i).Item(13).ToString
nereden = ds.Tables(0).Rows(i).Item(0).ToString
via = ds.Tables(0).Rows(i).Item(14).ToString
nereye = ds.Tables(0).Rows(i).Item(1).ToString
transit_sure = ds.Tables(0).Rows(i).Item(15).ToString
baslangic_tarihi = Convert.ToDateTime(ds.Tables(0).Rows(i).Item(2).ToString).ToString
e_kadar_gecerli = Convert.ToDateTime(ds.Tables(0).Rows(i).Item(3).ToString).ToString
kalem_kodu = ds.Tables(0).Rows(i).Item(7).ToString
fiyatlandirma = ds.Tables(0).Rows(i).Item(8).ToString
_20DRY = ds.Tables(0).Rows(i).Item(9).ToString
_40DRY = ds.Tables(0).Rows(i).Item(10).ToString
_40HDRY = ds.Tables(0).Rows(i).Item(11).ToString
_40HREF_NOR = ds.Tables(0).Rows(i).Item(12).ToString
kayit_eden = Environment.UserName.ToString
mysqlcommand.Parameters.AddWithValue("#line_isim", line_isim)
mysqlcommand.Parameters.AddWithValue("#nereden", nereden)
mysqlcommand.Parameters.AddWithValue("#via", via)
mysqlcommand.Parameters.AddWithValue("#nereye", nereye)
mysqlcommand.Parameters.AddWithValue("#transit_sure", transit_sure)
mysqlcommand.Parameters.AddWithValue("#baslangic_tarihi", baslangic_tarihi)
mysqlcommand.Parameters.AddWithValue("#e_kadar_gecerli", e_kadar_gecerli)
mysqlcommand.Parameters.AddWithValue("#kalem_kodu", kalem_kodu)
mysqlcommand.Parameters.AddWithValue("#fiyatlandirma", fiyatlandirma)
mysqlcommand.Parameters.AddWithValue("#20DRY", _20DRY)
mysqlcommand.Parameters.AddWithValue("#40DRY", _40DRY)
mysqlcommand.Parameters.AddWithValue("#40HDRY", _40HDRY)
mysqlcommand.Parameters.AddWithValue("#40HREF_NOR", _40HREF_NOR)
mysqlcommand.Parameters.AddWithValue("#kayit_eden", kayit_eden)
mysqlcommand.ExecuteNonQuery()
mysqlcommand.Parameters.Clear()
Next
If mysql_connection.State = ConnectionState.Open Then mysql_connection.Close()
End If
End If
ASPxGridView1.DataBind()

Crop image and save it in database using vb.net

I'm following a tutorial on Image Cropping with resizing using vb.net . Everything works well, But instead of saving it
on the hard disk. I want to save it on my database(SQLServer).
This is the code of saving on a disk
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cropSaveBtn.Click
Dim tempFileName As String
Dim svdlg As New SaveFileDialog()
svdlg.Filter = "JPEG files (*.jpg)|*.jpg|All files (*.*)|*.*"
svdlg.FilterIndex = 1
svdlg.RestoreDirectory = True
If svdlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
tempFileName = svdlg.FileName 'check the file exist else save the cropped image
Try
Dim img As Image = PreviewPictureBox.Image
SavePhoto(img, tempFileName, 225)
Catch exc As Exception
MsgBox("Error on Saving: " & exc.Message)
End Try
End If
End Sub
Public Function SavePhoto(ByVal src As Image, ByVal dest As String, ByVal w As Integer) As Boolean
Try
Dim imgTmp As System.Drawing.Image
Dim imgFoto As System.Drawing.Bitmap
imgTmp = src
imgFoto = New System.Drawing.Bitmap(w, 225)
Dim recDest As New Rectangle(0, 0, w, imgFoto.Height)
Dim gphCrop As Graphics = Graphics.FromImage(imgFoto)
gphCrop.SmoothingMode = SmoothingMode.HighQuality
gphCrop.CompositingQuality = CompositingQuality.HighQuality
gphCrop.InterpolationMode = InterpolationMode.High
gphCrop.DrawImage(imgTmp, recDest, 0, 0, imgTmp.Width, imgTmp.Height, GraphicsUnit.Pixel)
Dim myEncoder As System.Drawing.Imaging.Encoder
Dim myEncoderParameter As System.Drawing.Imaging.EncoderParameter
Dim myEncoderParameters As System.Drawing.Imaging.EncoderParameters
Dim arrayICI() As System.Drawing.Imaging.ImageCodecInfo = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()
Dim jpegICI As System.Drawing.Imaging.ImageCodecInfo = Nothing
Dim x As Integer = 0
For x = 0 To arrayICI.Length - 1
If (arrayICI(x).FormatDescription.Equals("JPEG")) Then
jpegICI = arrayICI(x)
Exit For
End If
Next
myEncoder = System.Drawing.Imaging.Encoder.Quality
myEncoderParameters = New System.Drawing.Imaging.EncoderParameters(1)
myEncoderParameter = New System.Drawing.Imaging.EncoderParameter(myEncoder, 60L)
myEncoderParameters.Param(0) = myEncoderParameter
imgFoto.Save(dest, jpegICI, myEncoderParameters)
imgFoto.Dispose()
imgTmp.Dispose()
Catch ex As Exception
End Try
End Function
I want it to save the picture to SQL Server 2008 (Image data type) together with my two data just like this
Using cmd As New SqlClient.SqlCommand("dbo.uspAdd", cn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#firstname", SqlDbType.VarChar, 100).Value = txtName.Text
cmd.Parameters.Add("#lastName", SqlDbType.VarChar, 100).Value = txtSurname.Text
'add insert picture code here
cmd.ExecuteNonQuery()
MsgBox("Save Record New record Successfully")
End Using
And now i'm stuck for almost 8 hours finding ways on how to fix this.Can anyone help me to solve this. Any help would be very much appreciated.
I would suggest converting the image to Base64 and then storing it as a string.
Then when you want to get the image back you need to convert it back from Base64 to an image.
You can convert an image to Base64 using this code:
Public Function ConvertImageToBase64(ByRef img As Image, ByVal format As System.Drawing.Imaging.ImageFormat) As String
Dim ImgStream As MemoryStream = New MemoryStream()
img.Save(ImgStream, format)
ImgStream.Close()
Dim ByteArray() As Byte = ImgStream.ToArray()
ImgStream.Dispose()
Return Convert.ToBase64String(ByteArray)
End Function
(http://www.dailycoding.com/posts/convert_image_to_base64_string_and_base64_string_to_image.aspx)
And to convert it back to an image you can use this code:
Public Function ConvertBase64ToImage(ByVal base64 As String) As Image
Dim img As System.Drawing.Image
Dim MS As System.IO.MemoryStream = New System.IO.MemoryStream
Dim b64 As String = base64.Replace(" ", "+")
Dim b() As Byte
b = Convert.FromBase64String(b64)
MS = New System.IO.MemoryStream(b)
img = System.Drawing.Image.FromStream(MS)
Return img
End Function
(http://snipplr.com/view/27514/vbnet-base64-to-image/)
Now you can basically add the image as a string, like this:
Dim Base64Bitmap As String = ConvertImageToBase64(img, System.Drawing.Imaging.ImageFormat.Png)
cmd.Parameters.Add("#Image", SqlDbType.VarChar, Base64Bitmap.Length).Value = Base64Bitmap

When I try to pull nvarchar column value that has an emojis stored in it, the data in VB.net it displays as '??'

When I try to pull the emoji value from the database using VB.net the emoji is displayed as '??'
Is there some sort of conversion I need to do in my stored procedure?
Private Function DisplayEmoji(input As String) As String
Dim output As New StringBuilder()
Dim enumerator = StringInfo.GetTextElementEnumerator(input)
While enumerator.MoveNext()
Dim chunk As String = enumerator.GetTextElement()
If Char.IsSurrogatePair(chunk, 0) Then
output.Append("<img src=""" + "https://abs.twimg.com/emoji/v1/72x72/" + Char.ConvertToUtf32(chunk, 0).ToString("x") + ".png"" style=""height:1.5em; width:1.5em;"">")
Else
output.Append(chunk)
End If
End While
Return output.ToString()
End Function
Or insert your image Blob type and read sql.
Dim filePath As String = Server.MapPath("APP_DATA/test.png")
Dim filename As String = Path.GetFileName(filePath)
Dim fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim br As BinaryReader = New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
Insert to Database yor image
Dim strQuery As String = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value = "image/png"
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
InsertUpdateData
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.
ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection(strConnString)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
con.Close()
con.Dispose()
End Try
End Function

DataGridView ScrollBar bug

When I get data for the DataGridView, my form freezes until the While loop completes, but then my scrollbar worked fine. I tried calling Application.DoEvents(); but that didn't work either.
If I get the data in a thread, then my form does not freeze, but the scrollbar disables and does not work after the While completes. I tried a BackgroundWorker but the scrollbar has a problem when using that too.
Private Sub dg()
myth = New Threading.Thread(AddressOf dgd)
myth.IsBackground = True
myth.Start()
End Sub
Private Sub dgd()
Dim x As Integer
If DataGridView1.Rows.Count = 0 Then x = 0 Else x = DataGridView1.Rows.Count
Try
Dim conn35a As New OleDbConnection("connstring")
Dim cmd35a As New OleDbCommand
cmd35a.CommandText = "Select count(*) from asd where downur Is Null"
cmd35a.CommandType = CommandType.Text
cmd35a.Connection = conn35a
conn35a.Open()
Dim returnValueaa As Integer = cmd35a.ExecuteScalar()
conn35a.Close()
Dim komut As String = "Select * from asd where downur Is Null"
Dim conn2 As New OleDbConnection("connstring")
conn2.Open()
Dim cmd2 As New OleDbCommand(komut, conn2)
Dim dr2 As OleDbDataReader = cmd2.ExecuteReader
If dr2.HasRows Then
While dr2.Read
Dim conn35 As New OleDbConnection("connstring")
Dim cmd35 As New OleDbCommand
cmd35.CommandText = "select count(*) from grid where ur = '" + dr2.Item("ur").ToString + "'"
cmd35.CommandType = CommandType.Text
cmd35.Connection = conn35
conn35.Open()
Dim returnValuea = cmd35.ExecuteScalar()
conn35.Close()
If returnValuea = 0 Then
DataGridView1.Rows.Add()
DataGridView1.Rows.Item(x).Cells(0).Value = x + 1
DataGridView1.Rows.Item(x).Cells(4).Value = "ID"
DataGridView1.Rows.Item(x).Cells(5).Value = dr2.Item("ur").ToString
DataGridView1.Rows.Item(x).Cells(6).Value = dr2.Item("ch").ToString
DataGridView1.Rows.Item(x).Cells(7).Value = dr2.Item("ti").ToString
DataGridView1.Rows.Item(x).Cells(8).Value = ".."
Dim client2 As New WebClient
Dim url As String = dr2.Item("pic").ToString
DataGridView1.Rows.Item(x).Cells(12).Value = New Bitmap(New MemoryStream(client2.DownloadData(url)))
DataGridView1.Rows.Item(x).Cells(13).Value = dr2.Item("vi")
DataGridView1.Rows.Item(x).Cells(14).Value = dr2.Item("su").ToString()
Dim con4 As New OleDbConnection("connstring")
con4.Open()
Dim cmd5 = New OleDbCommand("INSERT INTO grid (ur) VALUES (#ur)", con4)
cmd5.CommandType = CommandType.Text
cmd5.Parameters.Add("#ur", OleDbType.VarChar, 500).Value = dr2.Item("ur").ToString
cmd5.ExecuteNonQuery()
con4.Close()
x += 1
End If
End While
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I had the same problem.
I solved this by removing the Thread and calling the method directly