在asp中回发后,DropDownList选择的索引发生了变化

时间:2017-05-28 14:13:42

标签: c# asp.net .net

我首先在我的网页上有3个DropDownList用于州,第二个用于区域,第三个用于城市。

<asp:DropDownList ID="stateddl" OnSelectedIndexChanged="stateddl_SelectedIndexChanged" AutoPostBack="true" runat="server" CssClass="form-control"></asp:DropDownList>
                Select District:
               <asp:DropDownList ID="districtddl" OnSelectedIndexChanged="districtddl_SelectedIndexChanged" AutoPostBack="true" runat="server" CssClass="form-control" ViewStateMode="Enabled"></asp:DropDownList>
                Select Area:
               <asp:DropDownList ID="cityddl" runat="server" CssClass="form-control"></asp:DropDownList>

背后的代码

protected void districtddl_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            SqlConnection con2 = new SqlConnection("my connection");
            SqlCommand com = new SqlCommand("select DISTINCT Districtname,location from indiapincodes where statename =@statename and Districtname=@districtname order by Districtname", con2);
            SqlDataAdapter adpt = new SqlDataAdapter(com);
            com.Parameters.AddWithValue("@statename", stateddl.SelectedValue.ToString());
            com.Parameters.AddWithValue("@districtname", districtddl.SelectedValue.ToString());
            DataTable dt2 = new DataTable();
            adpt.Fill(dt2);
            cityddl.DataSource = dt2;
            cityddl.DataBind();
            cityddl.DataTextField = "location";
            cityddl.DataBind();
            con2.Close();
            con2.Dispose();
        }
        catch (Exception ex)
        {
        }
    }

如果用户选择任何状态,则在页面加载时从db填充状态,然后在selectedindexchanged事件上加载所选状态的所有区域。 但问题是,如果用户选择任何状态selectedindexchanged事件触发和回发。回发后DropDownList每次都选择ddl的第一个值。 我怎么解决这个问题。抱歉我的英语不好。

2 个答案:

答案 0 :(得分:0)

在没有查看您的Page_Load事件的情况下,您很可能在每次回发时运行下拉列表的初始填充。 您需要做的是使用Page.IsPostBack检查页面加载事件中的初始加载,它会告诉您页面是否第一次访问服务器。

private void Page_Load()
{
    if (!Page.IsPostBack)
    {
        YourPopulationOfDdFunction();
    }
}

答案 1 :(得分:0)

    Narender Godara! i think the issue is when u call first drop down on page load u have to use condition
    if(!ispostback)
    {
    //code of first dropdown %states
    } 
    then u have to write the next code in the selectedindexchanged of first dropdown and so on....
by the way your english is better than many developers of aisa, so bro keep it up, stay blessed,
#Good Luck