08/06/2014

How to Insert Image in SQL Database? Vb.Net Code


            Dim fInfo As New FileInfo(TxtImagePath.Text)
            Dim len As Long = fInfo.Length
            Dim stream As New FileStream(TxtImagePath.Text(), FileMode.Open)
            Dim imgData() As Byte = New Byte(Convert.ToInt32(len - 1)) {}
            stream.Read(imgData, 0, len)
            Dim Mycon As New SqlConnection(con)
            Mycon.Open()
            Dim cmd As SqlCommand
            Dim rowsaffected As Integer
            If BtnSave.Text = "&Update" Then
                cmd = New SqlCommand("sptbltrainees_DetailUpdate", Mycon)
                cmd.CommandType = CommandType.StoredProcedure
                cmd.Parameters.AddWithValue("@PISNO", txtPisNo.Text)
                cmd.Parameters.AddWithValue("@Rank", CbRank.SelectedIndex)
                cmd.Parameters.AddWithValue("@Name", TxtName.Text)
                cmd.Parameters.AddWithValue("@Organisation", CbOrg.SelectedIndex)
                cmd.Parameters.AddWithValue("@Unit", CbUnit.Text)
                cmd.Parameters.AddWithValue("@Image", imgData)
                rowsaffected = cmd.ExecuteNonQuery
                MessageBox.Show(rowsaffected.ToString & "  - row(s) Updated")
                BtnEdit.Enabled = True
                GroupBox1.Enabled = False
                BtnAdd.Enabled = True
                BtnDelete.Enabled = True
                BtnFind.Enabled = True
                BtnSave.Enabled = False
                BtnSave.Text = "&Save"
            Else
                cmd = New SqlCommand("sptbltrainees_DetailInsert", Mycon)
                cmd.CommandType = CommandType.StoredProcedure
                cmd.Parameters.AddWithValue("@PISNO", txtPisNo.Text)
                cmd.Parameters.AddWithValue("@Rank", CbRank.SelectedIndex)
                cmd.Parameters.AddWithValue("@Name", TxtName.Text)
                cmd.Parameters.AddWithValue("@Organisation", CbOrg.SelectedIndex)
                cmd.Parameters.AddWithValue("@Unit", CbUnit.Text)
                cmd.Parameters.AddWithValue("@Image", imgData)
                rowsaffected = cmd.ExecuteNonQuery
                MessageBox.Show(rowsaffected.ToString & "  - row(s) added")
What & How