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

Source: Internet
Author: User
ASP.net This code is written in response to a, posted on one of Charles Carroll ' s asp.net lists. Can sign up for one or all of the lists.
Code:

<%@ Page language= "VB"%>
<%@ Import namespace= "System.Data"%>
<%@ Import namespace= "System.Data.SqlClient"%>
<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>



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.