Dev
Dev

Reputation: 360

how to insert an image in sql database directly from picture box vb dotnet

I want to insert an image in .mdf file directly from the Picture Box, without using FileInfo.

Is it possible to do this ?? If yes then plz answer. Thanks in advance Dev..

Upvotes: 0

Views: 10114

Answers (2)

Romias
Romias

Reputation: 14133

Yes... it is possible!

Once you set the image to the Picture Box, you then can retrieve it the same way.

Image img = myPictureBox.Image

Now take that image and save it in database or save it in hard disk and just save in database the file path.

Upvotes: 0

Gabriel
Gabriel

Reputation: 2021

Lets say you have in aspx page:

<input id="File1" type="file" runat="server"/>
<asp:Button ID="OnUpload" runat="server" Text="Upload" />

And in vb page

Protected Sub OnUpload_Click(sender As Object, e As EventArgs) Handles OnUpload.Click
    ' Create a byte[] from the input file
    Dim len As Integer = File1.PostedFile.ContentLength
    Dim pic As Byte() = New Byte(len - 1) {}
    File1.PostedFile.InputStream.Read(pic, 0, len)
    ' Insert the image and comment into the database
    Dim connection As New SqlConnection("server=localhost;database=gallery;uid=yourusername;pwd=yourpassword")
    Try
        connection.Open()
        Dim cmd As New SqlCommand("insert into Image " & "(Picture) values (@image)", connection)
        cmd.Parameters.Add("@image", SqlDbType.Image, pic.Length).Value = pic
        cmd.ExecuteNonQuery()
    Finally
        connection.Close()
    End Try

End Sub

To insert an image into a SQL Server first make sure the data type of the column the image is being added to is the Image data type.

Give it a try...

And you can find here some examples: http://infynet.wordpress.com/2010/09/29/store-image-in-sql-database-using-vb-net/

On the other hand it's not recommended to save pictures in the database, your database will turn huge in no time and backups and restore will turn impossible.

Upvotes: 1

Related Questions