Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Configuration
Partial Class SelectSqlCommandVB
Inherits System.Web.UI.Page
Private sqlConnection As SqlConnection
Private sqlCommandString As String
Private TableID As String
Private TableData As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sqlConnectionString As String = WebConfigurationManager.ConnectionStrings("SqlConnectionString").ToString()
sqlConnection = New SqlConnection(sqlConnectionString)
sqlCommandString = "Select * From [TableDay]" 'กำหนดค่า initial ให้ sqlCommandString
TableID = "DayID" 'มันคือชื่อฟิลด์
TableData = "DayName" 'มันคือชื่อฟิลด์
If Not IsPostBack Then
'ป้อน ListItem ให้ DropDownList1
DropDownList1.Items.Add(New ListItem("ตารางวัน", "Day"))
DropDownList1.Items.Add(New ListItem("ตารางเดือน", "Month"))
DropDownList1.Items(0).Selected = True
End If
DropDownList1.AutoPostBack = True
BindData()
End Sub
Private Sub BindData()
Dim sqlCommand As SqlCommand = New SqlCommand(sqlCommandString, sqlConnection)
Dim sqlDataAdapter As SqlDataAdapter = New SqlDataAdapter(sqlCommand)
Dim Dt As DataTable = New DataTable()
sqlDataAdapter.Fill(Dt)
DataList1.DataSource = Dt
DataList1.DataBind()
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
Select Case DropDownList1.SelectedItem.Value
Case "Day"
sqlCommandString = "Select * From [TableDay]"
TableID = "DayID" 'มันคือชื่อฟิลด์
TableData = "DayName" 'มันคือชื่อฟิลด์
Case "Month"
sqlCommandString = "Select * From [TableMonth]"
TableID = "MonthID" 'มันคือชื่อฟิลด์
TableData = "MonthName" 'มันคือชื่อฟิลด์
End Select
BindData()
End Sub
Protected Sub DataList1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList1.ItemDataBound
Dim LabelBind1 As Label = CType(e.Item.FindControl("Label1"), Label)
Dim LabelBind2 As Label = CType(e.Item.FindControl("Label2"), Label)
If Not IsNothing(LabelBind1) Then
LabelBind1.Text = DataBinder.Eval(e.Item.DataItem, TableID).ToString()
End If
If Not IsNothing(LabelBind2) Then
LabelBind2.Text = DataBinder.Eval(e.Item.DataItem, TableData).ToString()
End If
End Sub
End Class