Dropdownlist回发到默认选定值

本文关键字:默认 Dropdownlist | 更新日期: 2023-09-27 18:20:07

当我在下拉列表中选择一个值时,我会得到一个回发,并且即使在回发之后也会选择我选择的值。如何获得默认值&lt--回发后是否再次选择城市-->作为选定值?

HTML:

<asp:DropDownList ID="ddlCity" Width="200px" runat="server" AutoPostBack="true"
 OnSelectedIndexChanged="ddlCity_SelectedIndexChanged"> </asp:DropDownList>

标记:

protected void Page_Load(object sender, EventArgs e)
{
    DataTable CityMembersTable = GetCity();
    ddlCity.DataSource = CityMembersTable;
    ddlCity.DataTextField = "CityName";
    ddlCity.DataValueField = "CityID";
    ddlCity.DataBind();
    ddlCity.Items.Insert(0, new ListItem("<--Choose City-->", ""));
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ddlCity.SelectedValue == "")
    {
        return;
    }
    ddlCity.SelectedValue == "0"; //Dose not work...
}

Dropdownlist回发到默认选定值

您需要首先在页面加载时处理IsPostBack,因为您在页面加载中绑定下拉列表。此外,如果执行了if条件,则ddlCity.SelectedValue == "0";将不会执行。

 protected void Page_Load(object sender, EventArgs e)
 {
      if(Page.IsPostBack == false)
      {
         DataTable CityMembersTable = GetCity();
         ddlCity.DataSource = CityMembersTable;
         ddlCity.DataTextField = "CityName";
         ddlCity.DataValueField = "CityID";
         ddlCity.DataBind();
         ddlCity.Items.Insert(0, new ListItem("<--Choose City-->", ""));
      }
 }

 protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
 {
    ddlCity.SelectedIndex = 0; //Put this here
    if (ddlCity.SelectedValue == "")
    {
        return;
    }
 }

尝试使用SelectedIndex = 0而不是SelectedValue。绑定数据后,您在位置0添加了值。

如果请求是PostBack,那么在绑定数据源之前,最好在Page_Load中添加一个额外的检查:

if (!Page.IsPostBack)
{
   //bind data
} 

如果这是您的确切代码,那么您正在比较ddl。针对"0"选择的值。相反,您希望使用assign运算符=而不是==。

如果它仍然不起作用。尝试ddlCity.SelectedIndex = 0;