如果在page_load事件中更改了索引,则下拉列表SelectedIndexChanged事件不会触发

本文关键字:事件 SelectedIndexChanged 下拉列表 索引 page load 如果 | 更新日期: 2023-09-27 18:26:52

我有一个下拉菜单&标签,下拉列表与字典绑定。当用户更改下拉列表的选定值时,我想更新标签。以下代码运行良好,但我想设置标签的初始值,我在page_load中设置了所选索引的值,但事件不会触发。如何修复?有什么页面事件可以帮助我解决这个问题吗。我知道我可以使用javascript来修复它,但我不想使用JS。

 public partial class WebForm1 : System.Web.UI.Page
        {
                Dictionary<string, string> myDictionary = new Dictionary<string, string>();
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!this.IsPostBack)
                {
                    myDictionary.Add("1", "Test Address 1");
                    myDictionary.Add("2", "Test Address 2");
                    myDictionary.Add("3", "Test Address 3");
                    myDictionary.Add("4", "Test Address 4");
                    myDictionary.Add("5", "Test Address 5");
                    drpTest.DataSource = myDictionary;
                    drpTest.DataTextField = "Key";
                    drpTest.DataValueField = "Value";
                    drpTest.DataBind();
                    // I want to set the index & update the label lblAddress
                    drpTest.SelectedIndex = 2;

                }
            }
            protected void drpTest_SelectedIndexChanged(object sender, EventArgs e)
            {
                lblAddress.Text = drpTest.SelectedItem.Value;
            }

如果在page_load事件中更改了索引,则下拉列表SelectedIndexChanged事件不会触发

您应该在页面加载时调用此函数

drpTest_SelectedIndexChanged(null, null)

并且它不会正常触发,因为在初始化页面并准备用于客户端之后,您没有更改下拉选择的值

在页面加载时更改标签文本。请参见下文。

protected void Page_Load(object sender, EventArgs e)
{
     if (!this.IsPostBack)
     {
          myDictionary.Add("1", "Test Address 1");
          myDictionary.Add("2", "Test Address 2");
          myDictionary.Add("3", "Test Address 3");
          myDictionary.Add("4", "Test Address 4");
          myDictionary.Add("5", "Test Address 5");
          drpTest.DataSource = myDictionary;
          drpTest.DataTextField = "Key";
          drpTest.DataValueField = "Value";
          drpTest.DataBind();
          drpTest.SelectedIndex = 2;
          lblAddress.Text = drpTest.SelectedItem.Value;     **// add this**
     }
}

希望它对你有用。

定义下拉列表时,包括drpTest.AutoPostBack=true更改时,这将触发SelectedIndexChanged事件。