< script language="c#" runat="server" >
protected override void OnLoad(EventArgs args)
{
string[] options = {"one", "two", "three", "four"};
this.dropDownMenu1.DataSource = options;
this.dropDownMenu2.DataSource = options;
this.dropDownMenu3.DataSource = options;
//Extremely inefficient: this code makes a trip back to the
//server just to update some text in a div?
if(base.Page.IsPostBack)
{
this.myLabel.InnerHtml = this.dropDownMenu3.SelectedValue;
}
base.DataBind();
}
< script type="text/javascript" >
function updateLabel(menu)
{
//much more efficient: do the update client-side
var selectedText = menu[menu.selectedIndex].text;
document.getElementById("myLabel").innerHTML = selectedText;
}
< form contenteditable="false" id="form1" runat="server" >
All of these three drop down menus have the same options and update the same div ...
But they each do it differently. All have their datasources set server-side.
OPTION 1: An Html Control
Select: < select id="dropDownMenu1" runat="server" onchange="updateLabel(this);">
OPTION 2: An ASP.NET server-side asp:DropDownList control
Select me:< asp:DropDownList id="dropDownMenu2" runat="server" onchange="updateLabel(this);">
OPTION 3: An ASP.NET server-side control with an AutoPostBack
Select me:< asp:DropDownList id="dropDownMenu3" autopostback="true" runat="server">
< div id="myLabel" runat="server" style="font-size: 22pt; color: red;">???Listed below are links to blogs that reference this entry: How (not) To Update a Label/Div from a Drop Down Menu.
TrackBack URL for this entry: http://www.rootsilver.com/mt-tb.cgi/17
Another way to do this is to fire an SelectedIndexChanged event.
In the ASPX, add the onSelectedIndexChanged to your control:
asp:DropDownList ID="foo" runat="server" AutoPostBack="True" OnSelectedIndexChanged="foo_SelectedIndexChanged"
Then in your code behind,
protected void foo_SelectedIndexChanged(object sender, EventArgs e)
{
myLabel.Text = foo.SelectedValue.ToString();
}
Thanks for the comment. Using autopostback falls into category #3 of an unnecessary trip back to the server.