ASP.NET DataList Control - Visual Studio .NET 2003 (Framework 1.1) จากตัวอย่างก่อนหน้านี้จะเป็นการใช้งาน DataList และเขียนในรูปแบบของ ASP Style คือเขียนร่วมกับกับส่วนของ HTML Element แต่ในตัวอย่างนี้ผมได้ยกการเขียนร่วมกับ Visual Studio .NET 2003 ซึ่ง Run บน Framework 1.1 ในรูปแบบของ Code-Behind แยกในส่วนของ Tag และ Code ไว้คนล่ะส่วน
Imports System.Data
Imports System.Data.OleDb
Public Class DataList1
Inherits System.Web.UI.Page
#Region " Web Form Designer Generated Code "
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Protected WithEvents myDataList As DataList
Private designerPlaceholderDeclaration As System.Object
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
InitializeComponent()
End Sub
#End Region
Dim objConn As OleDbConnection
Dim objCmd As OleDbCommand
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim strConnString As String
strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
Server.MapPath("database/mydatabase.mdb") & ";"
objConn = New OleDbConnection(strConnString)
objConn.Open()
BindData()
End Sub
Private Sub BindData()
Dim strSQL As String
strSQL = "SELECT * FROM category"
Dim dtReader As OleDbDataReader
objCmd = New OleDbCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
'*** BindData to DataList ***'
myDataList.DataSource = dtReader
myDataList.DataBind()
dtReader.Close()
dtReader = Nothing
End Sub
Private Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Unload
objConn.Close()
objConn = Nothing
End Sub
Private Sub myDataList_ItemDataBound(ByVal sender As Object, ByVal e As DataListItemEventArgs) Handles myDataList.ItemDataBound
'*** Image ***'
Dim img As System.Web.UI.WebControls.Image = CType(e.Item.FindControl("imgPicture"), System.Web.UI.WebControls.Image)
If Not IsNothing(img) Then
img.ImageUrl = e.Item.DataItem("Picture")
'img.Attributes.Add("OnClick","window.location='https://www.thaicreate.com?CateID="&e.Item.DataItem("CategoryID")&"'")
'img.Style.Add("cursor","hand")
End If
'*** HyperLink ***'
Dim hplCate As HyperLink = CType(e.Item.FindControl("hplCategory"), HyperLink)
If Not IsNothing(hplCate) Then
hplCate.Text = e.Item.DataItem("CategoryName")
hplCate.ToolTip = e.Item.DataItem("CategoryName")
hplCate.NavigateUrl = "https://www.thaicreate.com?CateID=" & e.Item.DataItem("CategoryID")
End If
End Sub
End Class