ASP.NET: Dynamically set Text and Value fields for
2024-07-10 12:58:10
供稿:网友
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>