如果已在下拉列表中选择了Item,则不会触发SelectedIndexChanged事件?

假设我有2个项目的下拉列表,默认情况下,第一个项目被选中。 如果我选择单击下拉列表中的第一个项目,是否有一种方法可以让selectedIndexChanged事件仍然触发?

我可以通过将Dropdown的SelectedIndex设置为-1来实现吗?

好吧,这不起作用,大声笑,因为它不显示当前选择的值,所以它是误导。

我对此有一个问题是下拉列表用于排序。 我有排序半工作,如果我选择第二项,它将按升序排序,例如,但如果我想现在使用第二项降序排序,我必须选择另一项,然后返回到第二个项目。

即使我添加了Select By …我认为排序的最佳解决方案是在下拉列表中添加更多项目,例如:

排序号码(Asc)

排序编号(Desc)

排序字母(Asc)

排序字母(描述)

谢谢,XaiSoft

注意:这是基于问题的更新内容。

假设您有一个下拉列表和一个列表框(dropdownlist1和listbox1)

您可以在page_load事件中设置初始下拉列表,如下所示:

dropdownlist1.items.insert(0, "----Select Sort Method----") dropdownlist1.items.insert(1, new ListItem("Alphabetic Ascending", "AlphaAsc")) dropdownlist1.items.insert(2, new ListItem("Alphabetic Descending", "AlphaDesc")) dropdownlist1.items.insert(3, new ListItem("Numeric Ascending", "NumAsc")) dropdownlist1.items.insert(4, new ListItem("Numeric Descending", "NumDesc")) dropdownlist1.selectedindex = 0 

然后在你的dropdownlist1.selectedindexchanged事件中你会这样处理它:

 if dropdownlist1.selectedindex <> 0 then select case dropdownlist1.selectedvalue case "AlphaAsc" Insert Code to Sort ListBox1 Alphabetically in ascending order case "AlphaDesc" Insert Code to sort ListBox1 Alphabetically in descending order case "NumAsc" Insert code to sort ListBox1 Numerically in ascending order case "NumDesc" Insert code to sort ListBox1 Numerically in descending order end select end if 

注意:如果您希望在选择项目后立即进行排序,则需要确保将dropdownlist1的AutoPostBack属性设置为true。

遗憾的是:只有当用户将选择从一个项目更改为另一个项目时,才会触发该事件。

您可以考虑在列表顶部添加带有“请选择…”文本的项目。

如前所述,添加第一项文本以指示用户从列表中选择项目。

如果您是数据绑定项目,则需要在之后插入项目。

 Dropdownlist1.datasource = whatever Dropdownlist1.datatextfield = "Something" dropdownlist1.datavaluefield = "ValueField" dropdownlist1.databind dropdownlist1.items.insert(0, "----Select Something!----") dropdownlist1.selectedindex = 0 

然后在SelectedIndexChanged事件中,您可以通过将所有代码包装在if语句中来阻止对第一个项目的操作:

 If DropDownList1.SelectedIndex <> 0 then Do Your Work End If 

出于好奇,你的第一个项目应该是一个可选择的项目,还是像“选择下面的东西”? 因为您实际上可以将下拉列表的文本值设置为上述引用,并且它不是可选项,因此无论选择什么,selectedindexchanged将始终触发。

否则你将不得不做这样的事情:

 DropDownList1.Items.Insert(0, "Select an Item") DropDownList1.SelectedIndex = 0 

在你绑定你的控制之后。

编辑添加

我实际上是用下拉菜单做的:

 var a = new AddressesBLL(); cmbPersonAddress1.DataSource = a.GetAddresses(); cmbPersonAddress1.DataBind(); //Set the default text to the below text but don't let it be part of the selections on the drop down. cmbPersonAddress1.Text = "Please select an existing address..."; 

这不会使“请选择现有地址……”成为可选项。 当您公开ddl时,第一个可选项是第一个地址,因此selectedindexchanged将始终触发。