ASP.NET: Dynamically set Text and Value fields for a DropDow

80酷酷网    80kuku.com

  asp.netThis code was written in response to a message posted on one of Charles Carroll's ASP.NET lists. You can sign up for one or all of the lists here.
Code:

<% Page Language="VB" %>
<% Import Namespace="System.Data" %>
<% Import Namespace="System.Data.SqlClient" %>
<html>
<script language="VB" runat="server">
    Sub Page_Load(sender As Object, e As EventArgs)
    If Not IsPostBack Then
           DropDownList1.DataTextField = "pub_name"
       DropDownList1.DataValueField = "pub_id"
       BindList
        End If
    End Sub

    Sub ButtonClick(sender As Object, e As EventArgs)
    If sender.ID = "Button1" Then
       DropDownList1.DataTextField = "pub_id"
       DropDownList1.DataValueField = "pub_name"
    Else
           DropDownList1.DataTextField = "pub_name"
       DropDownList1.DataValueField = "pub_id"
    End If

    BindList

    Button1.Visible = "False"
    Button2.Visible = "True"
    End Sub

    Sub BindList()
    Dim myConnection As SqlConnection = new SqlConnection("Data Source=(local)\NetSDK; Trusted_Connection=Yes; Initial Catalog=pubs")

    Dim myCommand As SqlCommand = New SqlCommand("Select pub_id, pub_name From publishers", myConnection)
    
    myConnection.Open()

    DropDownList1.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
        DropDownList1.DataBind()

        DropDownList1.Items.Insert(0, "Select an Item")
    DropDownList1.SelectedIndex = 0
    End Sub

</script>
<body>
<form runat="Server">
<asp:DropDownList id="DropDownList1" runat="server" />
<asp:Button id="Button1" Text="Switch Em" OnClick="ButtonClick" runat="server" />
<asp:Button id="Button2" Text="Switch Em Back" OnClick="ButtonClick" Visible="False" runat="server" />
</form>
</body>
</html>

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: