手把手教你VB.NET DataGrid圖片顯示
學習VB.NET時,你可能會遇到VB.NET上傳圖片并在DataGrid中顯示的問題,這里將介紹VB.NET DataGrid顯示問題的解決方法,在這里拿出來和大家分享一下。
#T#一、程序功能
當上傳圖片大小超過8K或格式不符時禁止上傳,上傳通過之后,用VB.NET DataGrid顯示上傳的圖片
二、建立數據庫
在MSSQL的NorthWind數據庫中新建一個users表。
三、窗體設計:
1、新建ASP.NET Web應用程序,命名為DataGrid3,保存路徑為http://192.168.0.1/DataGrid3(注:我機子上的網站的IP是192.168.0.1的主目錄是D:\web文件夾)然后點擊確定。
2、在解決方案資源管理器窗口中,將WebForm1.aspx重命名為UpPicture.aspx,然后從工具箱中向窗體添加一個Label控件、一個BUtton按鈕.然后從一個HTML工具箱中向窗體添加一個File field控件窗體界面。
3、在解決方案資源管理器窗口中右擊項目,選擇添加-新項-Web窗體,名稱設為ViewPicture.aspx。然后在打開的窗體中添加一個DataGrid控件。
4、右擊DataGrid控件,再點擊下方的“屬性生成器”,打開“DataGrid屬性窗口”。在“DataGrid屬性窗口”點擊“列”,取消“在運行時自動創建列”前的對勾,向選定的列中添加一個綁定列,在頁眉文本中輸入“序號”,在數據字段中輸入ID。再向選定的列中添加一個綁定列,在頁眉文本中輸入“頭像”,在數據字段中輸入headimg。然后點擊確定。
四、VB.NET DataGrid代碼設計:
1、UpPicture.aspx
- Imports System.Data.SqlClient
- Public Class WebForm1
- Inherits System.Web.UI.Page
- '窗體代碼省略
- '上傳圖片
- Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
- Dim img As String
- '定義postedfile文件是儲存用戶上載的文件
- Dim postedfile As HttpPostedFile = File1.PostedFile
- '定義一個變量儲存用戶上載文件的大小
- Dim intImgSize As Int32
- '獲取用戶上傳文件的大小,
- intImgSize = postedfile.ContentLength
- '如果要上傳的文件不為空
- If intImgSize <> 0 Then
- '如果大于8K, 則禁止上傳
- If intImgSize > 8000 Then
- Label1.Text = "圖片太大"
- Exit Sub
- End If
- '定義一個變量儲存用戶上傳圖片的文件類型
- Dim strImgType As String = postedfile.ContentType
- '只接受.gif格式的圖片
- Dim filesplit() As String = Split(strImgType, "/")
- strImgType = filesplit(filesplit.Length - 1)
- If strImgType <> "gif" Then
- Label1.Text = "圖片格式不對"
- Exit Sub
- End If
- '儲存要上傳的文件的整個路徑
- filesplit = Split(postedfile.FileName, "\")
- '取得上傳文件的文件名
- Dim filename As String = filesplit(filesplit.Length - 1)
- '將上傳的圖片保存到服務器當前目錄的headimg文件夾中
- postedfile.SaveAs(Server.MapPath("headimg") & "\" & filename)
- '定義一個變量儲存服務器上當前上傳圖片的路徑
- Dim imgpath As String = "headimg\" & filename
- img = ""
- '將圖片儲存到數據庫
- Dim scon As New SqlConnection("server=localhost;database=northwind;uid=sa;pwd=123")
- scon.Open()
- Dim scom As New SqlCommand("insert into users values (@img)", scon)
- scom.Parameters.Add("@img", SqlDbType.VarChar).Value = img
- Try
- scom.ExecuteNonQuery()
- Catch ex As Exception
- End Try
- scon.Close()
- '轉到查看圖片窗口
- Response.Redirect("ViewPicture.aspx")
- End If
- End Sub
- End Class
2、ViewPicture.aspx代碼:
- Imports System.Data.SqlClient
- Public Class ViewPicture
- Inherits System.Web.UI.Page
- ‘窗體代碼省略
- Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
- Dim scon As New SqlConnection("server=localhost;database=northwind;uid=sa;pwd=123")
- Dim sda As New SqlDataAdapter("select * from users", scon)
- Dim ds As New DataSet
- Try
- sda.Fill(ds)
- Catch ex As Exception
- End Try
- DataGrid1.DataSource = ds
- DataGrid1.DataBind()
- End Sub
- End Class