开发者

Get selectedIndex from a dropdown list on submit

This is my first web page ever and I can't seem to find the correct way to get the selected index from a dropdown list. I don't need the selected index until the user presses the submit button. I've been testing everything I've found on the subject, but nothing is working.

I don't want the drop-down box to reset when the selection is made, which is what happens if I use postback=true or any selected index changed events. And, I still get an index of 0.

When I test, the selected index is always zero.

This runs on page load:

 ddlBudgetLineItem.DataSource = budget.BudgetLineItems;
 ddlBudgetLineItem.DataTextField = "Name";
 ddlBudgetLineItem.DataValueField = "BudgetLineItemID";
 ddlBudgetLineItem.DataBind();

This is the drop-down list:

<asp:DropDownList ID="ddlBudgetLineItem" runat="server">
            </asp:DropDownList>

Here is the code that needs the index:

protected void submitPayment()
    {            
        string amountValue = txtAmount.Text.ToString();

        float amount = float.Parse(amountValue);

        Payment payment = new Payment()
        {
            Amount = amount,
            Payee = txtPayee.Text,
            BudgetLineItem = budget.BudgetLineItems[ddlBudgetLineItem.SelectedIndex],
            Memo = txtMemo.Text,
            PaymentDate = DateTime.Parse(txtPaymentDate.Text开发者_开发技巧),
            ExtraUserInfo = info
        };

        provider.AddPayment(payment);
    }

Any assistance is appreciated.


it seems to be a life cycle issue, this is happening because everytime (on a postback or not) the page is loaded, your dropdown is rebuilt (caused by ddlBudgetLineItem.DataBind()), concluding that on a postback your ddl will get index=0 forever.

how can you solve this:

1: Override the page databind method and put your code before call base.databind(); (inside the method)

2: on your load event you just have to call databind (if not is postback), it prevent to rebuild your object states everytime your page is loaded.(cause of your lost information).

3: take a look on a page lifecycle it will help you to prevent future issues like that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜