3

OnSelectedIndexChanged事件不会触发我的下拉框。我看过的所有论坛都告诉我添加AutoPostBack="true",但这并没有改变结果。Dropdown OnSelectedIndexChanged not firing

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编码器?

编辑:添加更多的代码背后


格雷厄姆·克拉克在需要的!Page.IsPostBack正确的,但现在是用的东西,我设置的全局变量。这段代码是从C#项目中拖放的,因此我认为全局变量和asp.net存在一些问题。我需要做更多的研究来了解全局变量如何在独立程序中与Web程序不同。

+2

你确定它不是射击吗?你有没有在foreach之外设置一个断点?这可能是一个不相关的问题,会导致你相信它没有被解雇。 – ctorx 2010-06-08 14:56:59

+2

你如何将数据绑定到下拉菜单?你的标记显示一个空的下拉菜单。你是否在后面的代码中绑定了它的值? – 2010-06-08 14:59:09

+0

@matthew:是的,它不会在foreach循环之外触发。 @KP:我在后面的代码中设置时区信息。 – Jim 2010-06-08 15:04:47

回答

9

您是否每次回到服务器或回发时都将数据绑定到您的下拉列表中?如果你每次都这样做,可能是因为服务器认为没有选择任何东西,因此事件不会触发。

假设您要对Page_Load事件中的下拉列表进行数据绑定。你想这样做:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!Page.IsPostBack) 
    { 
     // bind drop-down list here 
    } 
}