【发布时间】:2010-06-08 14:45:57
【问题描述】:
OnSelectedIndexChanged 事件未针对我的下拉框触发。我看过的所有论坛都告诉我添加AutoPostBack="true",但这并没有改变结果。
HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Current Time: " /><br />
<asp:Label ID="lblCurrent" runat="server" Text="Label" /><br /><br />
<asp:DropDownList ID="cboSelectedLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="cboSelectedLocation_SelectedIndexChanged" /><br /><br />
<asp:Label ID="lblSelectedTime" runat="server" Text="Label" />
</div>
</form>
</body>
</html>
后面的代码:
public partial class _Default : Page
{
string _sLocation = string.Empty;
string _sCurrentLoc = string.Empty;
TimeSpan _tsSelectedTime;
protected void Page_Load(object sender, EventArgs e)
{
AddTimeZones();
cboSelectedLocation.Focus();
lblCurrent.Text = "Currently in " + _sCurrentLoc + Environment.NewLine + DateTime.Now;
lblSelectedTime.Text = _sLocation + ":" + Environment.NewLine + DateTime.UtcNow.Add(_tsSelectedTime);
}
//adds all timezone displaynames to combobox
//defaults combo location to seoul, South Korea
//defaults current location to current location
private void AddTimeZones()
{
foreach(TimeZoneInfo tz in System.TimeZoneInfo.GetSystemTimeZones())
{
string s = tz.DisplayName;
cboSelectedLocation.Items.Add(s);
if (tz.StandardName == "Korea Standard Time") cboSelectedLocation.Text = s;
if (tz.StandardName == System.TimeZone.CurrentTimeZone.StandardName) _sCurrentLoc = tz.StandardName;
}
}
//changes timezone name and time depending on what is selected in the cbobox.
protected void cboSelectedLocation_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (TimeZoneInfo tz in System.TimeZoneInfo.GetSystemTimeZones())
{
if (cboSelectedLocation.Text == tz.DisplayName)
{
_sLocation = tz.StandardName;
_tsSelectedTime = tz.GetUtcOffset(DateTime.UtcNow);
}
}
}
}
对于新手 asp 编码员应该注意什么有什么建议吗?
编辑:在后面添加更多代码
Graham Clark 需要!Page.IsPostBack 是正确的,但现在它与我设置的全局变量有关。此代码是从 c# 项目中拖放的,因此我认为全局变量和 asp.net 存在一些问题。是时候让我对此进行更多研究,以了解全局变量在独立程序与 Web 程序中有何不同。
【问题讨论】:
-
你确定它没有触发吗?您是否在 foreach 之外设置了断点?这可能是一个不相关的问题,导致您相信它没有触发。
-
如何将数据绑定到下拉列表?您的标记显示一个空的下拉菜单。您是否在后面的代码中将值绑定到它?
-
@matthew:是的,它不会在 foreach 循环之外触发。 @KP:我在后面的代码中设置时区信息。
-
动态添加时区时也不会触发。
标签: c# asp.net drop-down-menu autopostback selectedindexchanged