ArgumentException when attempting to create image from stream - vb.net

there's an error showing up after i update the data in my datagridview and after i click the row of updated data in my datagridview this error will shown up
Private Sub DataGridView2_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView2.CellClick
Dim i As Integer
i = DataGridView2.CurrentRow.Index
Me.txtEmployeeID.Text = DataGridView2.Item(0, i).Value
Me.txtFirstName.Text = DataGridView2.Item(1, i).Value
Me.txtMiddleName.Text = DataGridView2.Item(2, i).Value
Me.txtLastName.Text = DataGridView2.Item(3, i).Value
Me.txtGender.Text = DataGridView2.Item(4, i).Value
Me.txtContactNumber.Text = DataGridView2.Item(5, i).Value
Me.txtupAge.Text = DataGridView2.Item(6, i).Value
Me.txtupAddress.Text = DataGridView2.Item(7, i).Value
Me.Bdate.Text = DataGridView2.Item(8, i).Value
Me.txtPos.Text = DataGridView2.Item(9, i).Value
If DataGridView2.Item(10, i).Value Is Nothing Then Return
Using m As MemoryStream = New MemoryStream(CType(DataGridView2.Item(10, i).Value, Byte()))
PictureBox2.Image = CType(Image.FromStream(m).Clone(), Image)
End Using
End Sub
**EDIT**
when im updating, the image type in my database will change into 0x which is no image are saved.
this is the code of my update
cn.Close()
cn.Open()
With cmd
.Connection = cn
.CommandText = ("Update TBL_EMPLOYEE SET FirstName= '" & txtFirstName.Text & "', MiddleName='" & txtMiddleName.Text & "',LastName='" & txtLastName.Text & "', Gender='" & txtGender.Text & "',Age='" & txtupAge.Text & "' ,Address='" & txtupAddress.Text & "', Position='" & txtPos.Text & "',BirthDate='" & Bdate.Value.Date & "', [Picture]=#PID where [EmployeeID]=#EID ")
.Parameters.AddWithValue("#EID", CInt(txtEmployeeID.Text))
.Parameters.Add("PID", SqlDbType.Image).Value = ms.ToArray()
.ExecuteNonQuery()
.Dispose()
.Parameters.Clear()
txtFirstName.Text = ""
txtMiddleName.Text = ""
txtLastName.Text = ""
txtGender.Text = ""
txtContactNumber.Text = ""
txtupAge.Text = ""
txtupAddress.Text = ""
txtPos.Text = ""
Bdate.Text = ""
PictureBox2.Image = Nothing
MsgBox("Employee Updated", vbInformation, "Information Message")
datagridshow()
End With
End If
when i update this image the image will not save. there's wrong syntax in my update

im missing this code : PictureBox2.Image.Save(ms, PictureBox2.Image.RawFormat) my bad. :'(

If you're sure DataGridView2.Item(10, i).Value has a value here then probably the MemoryStream is being Disposed too quickly. I'd suggest trying:
m As MemoryStream = New MemoryStream(CType(DataGridView2.Item(10, i).Value, Byte()))
PictureBox2.Image = Image.FromStream(m)
without Using

Related

How to edit the selected row when a button is clicked?

I was trying to edit the data from the selected rows in datagridview if the button is clicked and put it in the textbox to update the data and what's happening is if I select a row it is directly putted in the textboxes before I click the edit button, but what I want is if I select a row then click the edit button and the data from the selected rows will be putted in the textboxes provided. Can someone help me please..
here is my code in datagridview:
index = e.RowIndex
Dim selectedRow As DataGridViewRow
selectedRow = DataGridView1.Rows(index)
TextBox8.Text = selectedRow.Cells(1).Value.ToString
TextBox1.Text = selectedRow.Cells(2).Value.ToString
TextBox2.Text = selectedRow.Cells(3).Value.ToString
TextBox3.Text = selectedRow.Cells(4).Value.ToString
TextBox4.Text = selectedRow.Cells(5).Value.ToString
TextBox5.Text = selectedRow.Cells(6).Value.ToString
TextBox6.Text = selectedRow.Cells(7).Value.ToString
ComboBox1.Text = selectedRow.Cells(8).Value.ToString
TextBox9.Text = selectedRow.Cells(9).Value.ToString
then this is my code in edit button
Try
Dim cmd As New MySqlCommand
connect.Open()
cmd.Connection = connect
da = New MySqlDataAdapter("Select * from tbl_book_info", connect)
cmd.CommandText = "update tbl_book_info set (Title = '" & TextBox1.Text & "',Author = '" & TextBox2.Text & "',Copyright = '" & TextBox3.Text & "',Publisher = '" & TextBox4.Text & "',Place = '" & TextBox5.Text & "',Copies = '" & TextBox6.Text & "', Subject = '" & ComboBox1.Text & "', ClassNo = '" & TextBox8.Text & "',Registered by = '" & TextBox9.Text & "',Time = '" & TextBox10.Text & "',Date = '" & TextBox11.Text & "')"
cmd.ExecuteNonQuery()
MsgBox("Already Updated!")
MessageBox.Show("update tbl_book_info set (Title = '" & TextBox1.Text & "',Author = '" & TextBox2.Text & "',Copyright = '" & TextBox3.Text & "',Publisher = '" & TextBox4.Text & "',Place = '" & TextBox5.Text & "',Copies = '" & TextBox6.Text & "', Subject = '" & ComboBox1.Text & "', ClassNo = '" & TextBox8.Text & "',Registered by = '" & TextBox9.Text & "',Time = '" & TextBox10.Text & "',Date = '" & TextBox11.Text & "')")
data = New DataTable()
DataGridView1.DataSource = data
da = New MySqlDataAdapter("Select * from tbl_book_info", connect)
da.Fill(data)
Catch ex As Exception
End Try
Dim x As Integer
Dim y As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = DataGridView1.SelectedCells(0).Value()
x = DataGridView1.SelectedCells(0).RowIndex
y = DataGridView1.CurrentCell.ColumnIndex
DataGridView1.Enabled = False
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
DataGridView1.Enabled = True
DataGridView1.Rows(x).Cells(y).Value = TextBox1.Text
End Sub

VB.net and mysql data

i'm working an attendance system and its almost done but i have a problem in my time in and time out form. i already did the codes for time in and time out of students and its working quite well but my problem is after the day ends it must reset the data so it can gather a new data when another day starts.
this is my code for time in and out
Dim check As Boolean
Call connect()
Dim cmdd As New MySqlCommand("Select Count(*) from attendance_for_student WHERE Remarks = 'IN' ", dbconn)
Dim i As Integer = cmdd.ExecuteScalar()
cmdd = Nothing
dbconn.Close()
TextBox1 .Text = i
If student.Text = "" Then
MsgBox("Scan Your Code!", MsgBoxStyle.Critical)
Else
Call connect()
sql = "SELECT * FROM student WHERE Sbarcode='" & student.Text & "'"
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader
Do While dbread.Read
Dim id As String = student.Text
Dim folder As String = "c:\jpnhs\"
Dim filename As String = System.IO.Path.Combine(folder, id & ".bmp")
PictureBox1.Image = Image.FromFile(filename)
FULLNAME.Text = dbread.Item(1).ToString & " " & dbread.Item(2).ToString & " " & dbread.Item(3).ToString
Loop
dbread.Close()
dbconn.Close()
End If
If Len(student.Text) = 8 Then
Call connect()
check = False
sql = "SELECT * FROM attendance_for_student WHERE Sbarcode = '" & student.Text & "' AND (remarks <>'IN' OR remarks <>'OUT')"
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader
Do While dbread.Read
check = True
Loop
dbread.Close()
dbconn.Close()
If check = False Then
Call connect()
sql = "INSERT INTO attendance_for_student(Sbarcode,Time,Date,remarks) VALUES ('" & student.Text & "','" & LBLTime.Text & "','" & LBLDate.Text & "','IN')"
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader()
dbread.Close()
dbconn.Close()
Search_Code()
Else
Call connect()
sql = "INSERT INTO attendance_for_student(Sbarcode,Time,Date,remarks) VALUES ('" & student.Text & "','" & LBLTime.Text & "','" & LBLDate.Text & "','OUT')"
dbcomm = New MySqlCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader()
dbread.Close()
dbconn.Close()
Search_Code()
End If
End If

Save all rows in Datagridview when Checkbox column is true

Good Morning
I have a program that looks like this.
Form Design
I have a button named Multiple Select and when I click that the button will call SaveCheckedRecords() and here is the code for it
Public Sub SaveCheckedRecords()
Dim failed = False
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(0).Value = True Then
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Label2.Text = DataGridView1.Item("ItemCode", i).Value
Label3.Text = DataGridView1.Item("Description", i).Value
Label4.Text = DataGridView1.Item("ReflectedQty", i).Value
Label5.Text = DataGridView1.Item("UOM", i).Value
Label6.Text = DataGridView1.Item("UnitPrice", i).Value
Label7.Text = DataGridView1.Item("Total", i).Value
Label8.Text = DataGridView1.Item("Remarks", i).Value
standard() '<------------- Call this Sub
insert() '<------------- Call this Sub
failed = True
Exit For
End If
Next
If Not failed Then
MsgBox("Please select an item to receive")
End If
End Sub
Now my goal based on the code above is to transfer the data from datagridview rows to labels and call some Subs
Here is the code for the standard and insert
Private Sub standard()
Dim con As MySqlConnection = New MySqlConnection("server=localhost;userid=root;password=admin1950;database=inventory")
Dim cmd As MySqlCommand = New MySqlCommand("select StandardUOM,QtyPerUoM from item_master_list where ItemCode = '" & Label2.Text & "'", con)
Dim reader As MySqlDataReader
con.Open()
reader = cmd.ExecuteReader
While reader.Read
Label9.Text = reader.GetString("StandardUOM")
Label10.Text = reader.GetString("QtyPerUoM")
End While
End Sub
Private Sub insert()
DataGridView1.Columns.RemoveAt(0)
Dim con1 As MySqlConnection = New MySqlConnection("datasource=localhost;database=inventory;userid=root;password=admin1950")
Dim cmdinsert As MySqlCommand = New MySqlCommand("insert into receiving (RINo,PONo,ItemCode,Description,QtyPack,PackUoM,UnitPrice,Total,Remarks,ExpiryDate,QtyStan,StanUoM,PCS) values ('" & frm_Add_Receiving_Items.TextBox1.Text & "','" & Label1.Text & "','" & Label2.Text & "','" & Label3.Text & "','" & Label11.Text & "','" & Label5.Text & "','" & Label6.Text & "','" & Label7.Text & "','" & Label8.Text & "','" & DateTime.Now.ToString("yyyy-MM-dd") & "','" & Label12.Text & "','" & Label9.Text & "','" & Label10.Text & "')", con1)
con1.Open()
cmdinsert.ExecuteNonQuery()
con1.Close()
frm_Add_Receiving_Items.generate_rec_form()
updateRI()
loadlist1()
frm_Add_Receiving_Items.Button6.Enabled = False
Label2.Text = "Label2"
End Sub
All I want to do is to save the value of datagridview when checkboxcolumn(0) is True whats wrong with my code?
TYSM

Data gets stored in database from one tab page but it is not shown in another tab page in vb.net

I am using Visual Studio 2010 which has a form with a TabControl containing multiple tab pages.
1st tab page creates employee id and details about the employee which gets stored in the SQL server database successfully.2nd tab page has a ComboBox to display the employee id but it does not show the employee id which was created in the 1st tab page.When i close the project and run it again it displays the employee id.
How do i rectify this? Dim OpenDialog As New OpenFileDialog
With OpenDialog
.Filter = "Image Files (*.gif,*.jpg,*.jpeg,*.bmp,*.png)|*.gif;*.jpg;*.jpeg;*.bmp;*.png"
.Title = "Select A File"
End With
If gender.SelectedIndex = 0 Then
gend = "Male"
Else
gend = "Female"
End If
If eblood.SelectedIndex = 0 Then
blood = "A +ve"
ElseIf eblood.SelectedIndex = 1 Then
blood = "A -ve"
ElseIf eblood.SelectedIndex = 2 Then
blood = "B +ve"
ElseIf eblood.SelectedIndex = 3 Then
blood = "B -ve"
ElseIf eblood.SelectedIndex = 4 Then
blood = "AB +ve"
ElseIf eblood.SelectedIndex = 5 Then
blood = "AB -ve"
ElseIf eblood.SelectedIndex = 6 Then
blood = "O +ve"
Else
blood = "O -ve"
End If
If (String.IsNullOrWhiteSpace(eid.Text.Trim())) Or (String.IsNullOrWhiteSpace(fname.Text.Trim())) Or (String.IsNullOrWhiteSpace(lname.Text.Trim())) Or (String.IsNullOrWhiteSpace(gender.Text.Trim())) Or (String.IsNullOrWhiteSpace(gender.Text.Trim())) Or (String.IsNullOrWhiteSpace(country.Text.Trim())) Or (String.IsNullOrWhiteSpace(eaddress.Text.Trim())) Or (String.IsNullOrWhiteSpace(equali.Text.Trim())) Or (String.IsNullOrWhiteSpace(eblood.Text.Trim()) Or (String.IsNullOrWhiteSpace(TextBox_browse.Text.Trim()))) Then
MsgBox("Please Fill all the Fields", vbExclamation)
Else
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
myconnection = New SqlConnection("Data Source=localhost\sqlexpress;Initial Catalog=billing;Integrated Security=True")
Try
myconnection.Open()
mycommand = New SqlCommand("insert into b_emp_details([ed_id],[ed_first_name],[ed_last_name],[ed_dob],[ed_phone_number],[ed_gender],[ed_joining_date],[ed_country],[ed_address],[ed_qualification],[ed_blood_grp],[ed_image],[ed_created_by],[ed_created_date]) values ('" & eid.Text & "','" & fname.Text & "','" & lname.Text & "','" & dob.Text.ToString & "','" & ph.Text & "','" & gend & "','" & doj.Text.ToString & "','" & country.Text & "','" & eaddress.Text & "','" & equali.Text & "','" & blood & "','" & Trim(TextBox_browse.Text) & "','" & global_user & "','" & global_date & "')", myconnection)
mycommand.ExecuteNonQuery()
mycommand.CommandText = "UPDATE b_emp_details SET [ed_image] ='" & Trim(TextBox_browse.Text) & "' where [ed_id]='" & eid.Text & "'"
mycommand.Connection = myconnection
dr = mycommand.ExecuteReader
Dim newimage As New BitmapImage
newimage.BeginInit()
newimage.UriSource = (New Uri(OpenDialog.FileName, UriKind.RelativeOrAbsolute))
TextBox_browse.Text = OpenDialog.FileName
newimage.EndInit()
MessageBox.Show("Employee Successfully Created...")
eid.Text = ""
fname.Text = ""
lname.Text = ""
dob.Text = ""
ph.Text = ""
gender.Text = ""
doj.Text = ""
country.Text = ""
eaddress.Text = ""
equali.Text = ""
eblood.Text = ""
TextBox_browse.Text = ""
Call ResetBindings()
Catch ex As Exception
MsgBox("Error: " + ex.Message + "Invalid Data..Please Enter A Valid Data....")
'MsgBox("Invalid Data..Please Enter A Valid Data....")
myconnection.Close()
End Try
End If

My StreamReader ReadLine is reading every other line

I am looping through a text file and reading and then parsing each line.. then, inserting into a sql server. The problem is, I am getting every other line. Any thoughts?
I read another post on here that is similar and it says that that person was calling the ReadLine twice... which makes sense. I just cannot spot where it is happening.
Private Sub btnUpdateRSR_Click(sender As System.Object, e As System.EventArgs) Handles btnUpdateRSR.Click
' Get RSR File
lblStatus.Text = "Getting RSR File"
Application.DoEvents()
If chkDLRSR.Checked = True Then
ftpGetRSR()
End If
Application.DoEvents()
lblStatus.Text = "Got RSR File"
' Whack existing data
killRSRData()
' Run Update of Invnetory
Dim sCmd As New SqlCommand()
Dim fp As StreamReader
Dim MyFile As String = String.Empty
Dim dblRecordCount As Double
Try
'Open file with StreamReader
fp = File.OpenText("c:\ct_info\rsr.txt")
Catch err As Exception
lblStatus.Text = "File Read Failed! Reason: " & err.ToString()
End Try
sCmd.Connection = New System.Data.SqlClient.SqlConnection("Data Source=vortx-sql01.vortx.com;Initial Catalog=expresspolicesupply;Persist Security Info=True;User ID=expresspolicesupply;Password=blahblah")
sCmd.Connection.Open()
Dim strArr() As String
While String.IsNullOrEmpty(fp.ReadLine) = False ' fp.ReadLine.IsNullOrEmpty = False
MyFile = fp.ReadLine
strArr = MyFile.Split(";")
'Show what is in the second position of the array.
'MessageBox.Show(strArr(1))
Try
Dim RSRstocknumber As String = strArr(0)
Dim UPCcode As String = strArr(1)
Dim ProductDescription As String = Replace(strArr(2), "'", """")
Dim DepartmentNumber As String = strArr(3)
Dim ManufacturerID As String = strArr(4)
Dim RetailPrice As String = strArr(5)
Dim RSRRegularPrice As String = strArr(6)
Dim Weight As String = strArr(7)
Dim InventoryQuantity As String = strArr(8)
Dim Model As String = Replace(strArr(9), "'", """")
Dim FullManufacturerName As String = Replace(strArr(10), "'", """")
Dim ManufacturerPartNo As String = strArr(11)
Dim AllocatedCloseoutDeleted As String = strArr(12)
Dim ExpandedProductDescription As String = Replace(strArr(13), "'", """")
Dim ImageName As String = strArr(14)
lblStatusPrevious.Text = "Previous one: " & lblStatus.Text
lblStatus.Text = strArr(0)
Application.DoEvents()
With sCmd
.CommandText = "INSERT into rsr (rsrstocknumber, upccode, productDescription, departmentnumber, ManufacturerID, RetailPrice, RSRRegularPrice, Weight, InventoryQuantity, Model, FullManufacturerName, ManufacturerPartNo, AllocatedCloseoutDeleted, ExpandedProductDescription, ImageName) " & _
" Values('" & RSRstocknumber & "', '" & UPCcode & "', '" & ProductDescription & "', '" & DepartmentNumber & "', '" & ManufacturerID & "', '" & _
RetailPrice & "', '" & RSRRegularPrice & "', '" & Weight & "', '" & InventoryQuantity & "', '" & Model & "', '" & FullManufacturerName & "', '" & ManufacturerPartNo & "', '" & _
AllocatedCloseoutDeleted & "', '" & ExpandedProductDescription & "','" & ImageName & "');"
'MessageBox.Show(sCmd.CommandText.ToString)
.CommandType = CommandType.Text
.ExecuteNonQuery()
' Update record counter
dblRecordCount = dblRecordCount + 1
lblRecordCount.Text = dblRecordCount
Application.DoEvents()
End With
Catch ex As Exception
lblErrorLabel.Text = "Error on thown on " & lblRecordCount.Text
'MessageBox.Show("Error occurred! Details: " & ex.Message)
End Try
End While
fp.Close() 'Close file with StreamReader
sCmd.Connection.Close()
lblStatus.Text = "Updating website for RSR"
lblStatusPrevious.Text = ""
spUpdateRSR()
lblStatus.Text = "Done"
lblStatusPrevious.Text = ""
End Sub
That's because you're calling ReadLine() twice.
Every other line gets swallowed by String.IsNullOrEmpty(fp.ReadLine) = False.
You are calling ReadLine twice.
While String.IsNullOrEmpty(fp.ReadLine) = False ' fp.ReadLine.IsNullOrEmpty = False
MyFile = fp.ReadLine
Once in the IsNullOrEmpty check and once on MyFile = fp.ReadLine
This line is reading the file, and then you read the next one in the while loop:
While String.IsNullOrEmpty(fp.ReadLine) = False
You are calling it twice :)
You need to use this to check whether it is the end of the file:
While fp.EndOfStream = False