开发者

post back dropdownlist

开发者 https://www.devze.com 2023-03-26 17:40 出处:网络
on this site when dropdownlist contains only one item, when clicked it doesn\'t cause a post back protected void Page_Load(object sender, EventArgs e)

on this site when dropdownlist contains only one item, when clicked it doesn't cause a post back

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DropDownList1.Items.Add("a");

        DropDownList2.Items.Add("a");
        DropDownList2.Items.Add("b");

    }
}


protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Response.Write(DropDownList1.Text);//does not work ????????????
}
protected void DropDownList2_S开发者_如何转开发electedIndexChanged(object sender, EventArgs e)
{
    Response.Write(DropDownList2.Text);

}

on this site


DropDownList1_SelectedIndexChanged will never trigger because you only have 1 item in DropDownList1, thus index will never be changed.

Updated

What you can do is add a null value to the dropdownlist1, like so

<asp:DropDownList runat="server" ID="DropDownList1">
    <asp:ListItem Value="0" Text="Choose option" Selected="true" />
    <asp:ListItem Value="1" Text="a" />
</asp:DropDownList>


DropDownList1_SelectedIndexChanged won't trigger because the selected index is already a. A list of DropDownList Events can be found here DropDownList Events. The event DataBound should trigger, where you can do Response.Write(DropDownList1.Text);


May be you can add a new item at index 0 which says 'Select' and when user changes selection it will causes a post back...

DropDownList1.Items.Add("SELECT");
DropDownList1.Items.Add("a");


asp:DropDownList with AutoPostBack="true" renders as html select tag that has client side onchange event and a java-script function automatically generated to handle this client side onchange event.

i.e. if you have:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
    </asp:DropDownList>

the rendered page source looks like:

<select name="DropDownList1" onchange="javascript:setTimeout('__doPostBack(\'DropDownList1\',\'\')', 0)" id="DropDownList1">

as you see in order to postback the client side onchange event has to be triggered. clientside onchange will occur only if html select tag has two or more options select-able.

I see solutions are already posted, just thought would be nice to explain it in details.

In two words there have to be more than one asp:ListItem for the asp:DropDownList control.


I wanted a similar thing. Code below did it for me. Make sure it is the first code in your SelectedIndexChanged method.

//fixes error when postback 
    if (DropDownList.SelectedIndex == 0)
    {
       DropDownList.SelectedIndex = 1;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号