How to save and upload Image - asp.net

How I can upload and save image in ASP.net using with vb Language and SQL server 2008.

You can go with this tutorial.
A part from the link to save images in database:
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
If TextBox1.Text = "" Then
MsgBox("Fill the Name Field")
Else
Dim sql As String = "INSERT INTO Information VALUES(#name,#photo)"
Dim cmd As New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim ms As New MemoryStream()
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("#photo", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
MessageBox.Show("Name & Image has been saved", "Save", MessageBoxButtons.OK)
Label1.Visible = False
TextBox1.Visible = False
End If
End Sub
and here is how images retrieves:
Private Sub DataGridView1_CellMouseClick(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick
cmd = New SqlCommand("select photo from Information where name='" & _
DataGridView1.CurrentRow.Cells(0).Value() & "'", con)
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If Not imageData Is Nothing Then
Using ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
PictureBox1.BackgroundImage = Image.FromStream(ms, True)
End Using
End If
GroupBox2.SendToBack()
GroupBox2.Visible = False
Label1.Visible = True
Label1.Text = DataGridView1.CurrentRow.Cells(0).Value()
End Sub
Compare your findings with this sample and explore what you are missing.

Related

How do I call an image from a database of string type in ASP.Net?

This is my code for displaying the image:
<asp:image ID="Image3" runat="server" ImageUrl="AyoBelajar_Angka.aspx?id_bahan=7">
And this is my code-behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Request.QueryString("id_bahan") IsNot Nothing Then
Dim strQuery As String = "select nama,kategori, gambar from ayobelajar where id_bahan=#id_bahan"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id_bahan", SqlDbType.VarChar).Value() = Convert.ToInt32(Context.Request.QueryString("id_bahan"))
Dim dt As DataTable = GetData(cmd)
Dim bytes() As Byte = CType(dt.Rows(0)("gambar"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("kategori").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows(0)("nama").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
Convert your byte array to base64String string and then assign it to your image control.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Request.QueryString("id_bahan") IsNot Nothing Then
Dim strQuery As String = "select nama,kategori, gambar from ayobelajar where id_bahan=#id_bahan"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id_bahan", SqlDbType.VarChar).Value() = Convert.ToInt32(Context.Request.QueryString("id_bahan"))
Dim dt As DataTable = GetData(cmd)
Dim bytes() As Byte = CType(dt.Rows(0)("gambar"), Byte())
'Converting Byte array to ToBase64String
Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
Image3.ImageUrl = "data:image/png;base64," & base64String
End Sub
It seems from your code-behind that your image was saved as a byte array not a string. Your code-behind that you posted does not return a string, it returns binary data and that cannot be placed in the ImageUrl property which expects a string.
You can convert the image binary data to a Base64String which you can then put in the ImageUrl property. It's pretty easy to do the conversion:
Dim ImageString As String = Convert.ToBase64String(bytes, 0, bytes.Length)
However, you will have to prepend the string with the type of the image. If all your images are the same type, let's say jpg files, then that's easy:
ImageString = "data:image/jpg;base64," & ImageString
But if you have images of different types in the database, you'll have to detect the type of the image from the binary data. Here is how you can do so. But it seems that you have the type in dt.Rows(0)("kategori").ToString()?
Finally, you need to return the string, so here is the complete code (change the jpg to whatever your images type is):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Request.QueryString("id_bahan") IsNot Nothing Then
Dim strQuery As String = "select nama,kategori, gambar from ayobelajar where id_bahan=#id_bahan"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id_bahan", SqlDbType.VarChar).Value() = Convert.ToInt32(Context.Request.QueryString("id_bahan"))
Dim dt As DataTable = GetData(cmd)
Dim bytes() As Byte = CType(dt.Rows(0)("gambar"), Byte())
Dim ImageString As String = Convert.ToBase64String(bytes, 0, bytes.Length)
ImageString = "data:image/jpg;base64," & ImageString
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "text/plain"
Response.Write(ImageString)
Response.End()
Else
'I don't know what code you have here
End If
End Sub
Hi tam you are have a imagepath in database right you want to display that image. you can convert it in ToBase64String format and display or it can be done directly. if your path is properly.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
'From database get path and assign to imagePath variable
Dim imagePath As String = "~/Files/happy.jpg"
Dim filePath As String = Server.MapPath(imagePath)
' Will Convert filePath to bytes
Dim imageBytes As Byte() = File.ReadAllBytes(filePath)
'bytes array to ToBase64String
Dim base64String As String = Convert.ToBase64String(imageBytes, 0, imageBytes.Length)
'Attaching image to ToBase64String
Image3.ImageUrl = "data:image/jpg;base64," & base64String
End Sub
View
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %>.</h2>
<p>Your app description page.</p>
<p>Use this area to provide additional information.</p>
<asp:Image ID="Image3" runat="server" />
</asp:Content>
Output
Folder view

VB dot net session value set in text box not change

In one of my vb page i am setting the value of a textbox through the value coming from session. In the same page i want to perform an edit operation of the record. On the page load i displayed the variables in textboxes and after editing values when i submit and take the value from the textboxes, it still take the value i set through session. It do not take the value changed in the textbox rather it shows the value assigned at the time of page load. Please help.
Here is my code,
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.SessionState.HttpSessionState
Imports System.Drawing
Imports System.Drawing.Printing
Partial Class Default2
Inherits System.Web.UI.Page
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim var As String
var = Session("S2").ToString()
TextBox1.Text = var
Session.Remove("S2")
cmd = New SqlCommand("select * from HouseDetails where OccupantName= '" & TextBox1.Text & "' ", cn)
dr = cmd.ExecuteReader
While (dr.Read)
Label1.Text = dr(1)
Label2.Text = dr(2)
Label3.Text = dr(3)
TextBox3.Text = dr(4)
DropDownList3.SelectedItem.Text = dr(5)
TextBox2.Text = dr(6)
TextBox4.Text = dr(7)
TextBox5.Text = dr(8)
DropDownList4.Text = dr(9)
End While
cn.Close()
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim query As String = ("UPDATE HouseDetails SET OccupantName='" & TextBox1.Text & "' where HouseNum='" & Label3.Text & "'")
cmd = New SqlCommand(query, cn)
Dim x As Integer = cmd.ExecuteNonQuery()
cn.Close()
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class
Add postback prevention with the line "If (Page.IsPostBack = false) Then", for not assigning the same value again to the textbox,
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.SessionState.HttpSessionState
Imports System.Drawing
Imports System.Drawing.Printing
Partial Class Default2
Inherits System.Web.UI.Page
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Page.IsPostBack = false) Then
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim var As String
var = Session("S2").ToString()
TextBox1.Text = var
Session.Remove("S2")
cmd = New SqlCommand("select * from HouseDetails where OccupantName= '" & TextBox1.Text & "' ", cn)
dr = cmd.ExecuteReader
While (dr.Read)
Label1.Text = dr(1)
Label2.Text = dr(2)
Label3.Text = dr(3)
TextBox3.Text = dr(4)
DropDownList3.SelectedItem.Text = dr(5)
TextBox2.Text = dr(6)
TextBox4.Text = dr(7)
TextBox5.Text = dr(8)
DropDownList4.Text = dr(9)
End While
cn.Close()
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim query As String = ("UPDATE HouseDetails SET OccupantName='" & TextBox1.Text & "' where HouseNum='" & Label3.Text & "'")
cmd = New SqlCommand(query, cn)
Dim x As Integer = cmd.ExecuteNonQuery()
cn.Close()
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class
I fancy you're missing a check for IsPostBack to see whether or not this is a new request or a submission.
If (Not IsPostBack) Then
' populate for first load
End If
You have to put your code in IsPostback property.
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.SessionState.HttpSessionState
Imports System.Drawing
Imports System.Drawing.Printing
Partial Class Default2
Inherits System.Web.UI.Page
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (!IsPostBack) Then
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim var As String
var = Session("S2").ToString()
TextBox1.Text = var
Session.Remove("S2")
cmd = New SqlCommand("select * from HouseDetails where OccupantName= '" & TextBox1.Text & "' ", cn)
dr = cmd.ExecuteReader
While (dr.Read)
Label1.Text = dr(1)
Label2.Text = dr(2)
Label3.Text = dr(3)
TextBox3.Text = dr(4)
DropDownList3.SelectedItem.Text = dr(5)
TextBox2.Text = dr(6)
TextBox4.Text = dr(7)
TextBox5.Text = dr(8)
DropDownList4.Text = dr(9)
End While
cn.Close()
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim query As String = ("UPDATE HouseDetails SET OccupantName='" & TextBox1.Text & "' where HouseNum='" & Label3.Text & "'")
cmd = New SqlCommand(query, cn)
Dim x As Integer = cmd.ExecuteNonQuery()
cn.Close()
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class

ASP.NET Downloading files from an SQL table

I'm trying to download a file from an SQL Server table. I am using a GridView. Whenever I try to download a file, I get a corrupted file.
I am using ASP.NET and VB.NET with SQL Server 2012 Express.
Any ideas why ?
Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
Dim ContentID = Convert.ToInt32(GridView1.SelectedRow.Cells(1).Text)
Dim ContentName = GridView1.SelectedRow.Cells(2).Text
Dim ContentType = GridView1.SelectedRow.Cells(3).Text
lblContentName.Text = "[ " + ContentName + " ]"
lblContentName.Visible = True
End Sub
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
Dim cn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
If e.CommandName = "Download" Then
Dim filename As String = String.Empty
Dim id As Integer = Convert.ToInt32(e.CommandArgument)
Dim cmd As New SqlCommand("SELECT content_name,content_type,content_data FROM content WHERE content_id = " & id, cn)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
Dim bytes As Byte()
dr = cmd.ExecuteReader()
If dr.Read() Then
filename = dr("content_name").ToString()
Response.ContentType = dr("content_type").ToString()
Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
bytes = DirectCast(dr("content_file"), Byte())
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(bytes)
Response.Flush()
Response.[End]()
End If
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT content_id, content_name FROM content"
cmd.Connection = con
con.Open()
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
con.Close()
End Using
End Using
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGrid()
End If
End Sub

Unable to reflect changes in dataset or dataadapter on page reload

What is the problem in my this code?
The code is working fine but when i enter new record in table and refresh the page then the changes will not be reflected...
what was the problem iam confused..
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Dim ds As New DataSet()
Dim connStr As String = "Data Source=DOBRIYAL-PC;Initial Catalog=MenuDb;Integrated Security=True"
Using conn As New SqlConnection(connStr)
Dim sql As String = "Select MenuID, Text, Description, ParentID from Menu"
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(ds)
da.Dispose()
da.AcceptChangesDuringFill = True
End Using
ds.DataSetName = "Menus"
ds.Tables(0).TableName = "Menu"
ds.GetChanges()
Dim relation As New DataRelation("ParentChild", ds.Tables("Menu").Columns("MenuID"), ds.Tables("Menu").Columns("ParentID"), True)
relation.Nested = True
ds.Relations.Add(relation)
XmlDataSource1.Data = ds.GetXml()
If Request.Params("Sel") IsNot Nothing Then
Page.Controls.Add(New System.Web.UI.LiteralControl("You selected " + Request.Params("Sel")))
End If
XmlDataSource1.DataBind()
RadMenu1.DataBind()
End Sub
I have refatored your source code now you should see your new records on page load
Private Sub BindData()
Dim ds As New DataSet()
Dim connStr As String = "Data Source=DOBRIYAL-PC;Initial Catalog=MenuDb;Integrated Security=True"
Using conn As New SqlConnection(connStr)
Dim sql As String = "Select MenuID, Text, Description, ParentID from Menu"
Dim da As New SqlDataAdapter(sql, conn)
da.Fill(ds)
da.Dispose()
da.AcceptChangesDuringFill = True
End Using
ds.DataSetName = "Menus"
ds.Tables(0).TableName = "Menu"
ds.GetChanges()
Dim relation As New DataRelation("ParentChild", ds.Tables("Menu").Columns("MenuID"), ds.Tables("Menu").Columns("ParentID"), True)
relation.Nested = True
ds.Relations.Add(relation)
XmlDataSource1.Data = ds.GetXml()
If Request.Params("Sel") IsNot Nothing Then
Page.Controls.Add(New System.Web.UI.LiteralControl("You selected " + Request.Params("Sel")))
End If
XmlDataSource1.DataBind()
RadMenu1.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.BindData()
End Sub

asp.net Check if the string from a textBox exist in my access table

This is the code I try
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim ds As New DataSet
Dim strSQL As String = "SELECT * FROM Client WHERE UserName = '" & TextBox1.Text & "'"
Dim da As New OleDbDataAdapter(strSQL, con)
Try
con.Open()
Dim builder As New OleDbCommandBuilder(da)
da.Fill(da)
If ds.Tables.Count > 0 Then
MsgBox("exist")
Else
MsgBox("not exist")
End If
con.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The ds.table.count its every time = 1 whatever the TextBox1.Text.
Thanks for helping me to Check if the string from a textBox exist in my access table.

Resources