新客网WWW.XKER.COM:致力做中国最专业的网络学院!
学院: 操作系统 - 网络应用 - 服务器 - 网络安全 - 工具软件 - 办公软件 - Web开发 - 数据库 - 网页设计 - 图形图像 - 媒体动画 - 硬件学堂 - 存储频道 - QQ专区
您的位置:首页 > 软件开发 > .Net开发 > Asp.net教程 > 正文:ASP.NET: Dynamically set Text and Value fields for a DropDownList

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

新客网 XKER.COM 2003-07-12 来源: 收藏本文
This 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>

收藏】 【评论】 【推荐】 【投稿】 【打印】 【关闭
发表评论
要记得去论坛讨论,点击注册新会员匿名评论
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
阅读排行
随机推荐
实用信息推荐