我的下拉框中没有触发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程序中有所不同。
答案 0 :(得分:9)
您是将每次旅行的下拉列表数据绑定回服务器,还是只回发?如果你每次都这样做,可能是服务器认为没有选择任何东西,因此事件不会触发。
假设您正在对Page_Load事件中的下拉列表进行数据绑定。你想这样做:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// bind drop-down list here
}
}