2

I have a dropdownlist control and a button in asp.net page. The dropdownlist is populated from a method. If I select any item other than the first item, after clicking the button, I lose the selected item in the DDL and it selects the first item and also I am getting the value of the first item only in the button click event. How can I fix the problem?

 <asp:DropDownList ID="userDropDown" runat="server" DataTextField="CustomerName"  DataValueField="CustomerId">
</asp:DropDownList>

protected void Button1_Click(object sender, EventArgs e)
{
if(!page.isPostBack)
{
    userDropDown.DataSource = CC.GetCustomers();
    userDropDown.DataBind();
}
}
2
  • 1
    Your code can't compile. page doesn't exist. Commented Aug 23, 2013 at 16:59
  • 1
    It should be Page.IsPostBack (check case sensitivity). Also note that it should not be within Button1_Click event as button click is always Page.IsPostBack = true. Use Page_Load method instead. Commented Aug 23, 2013 at 17:16

3 Answers 3

2

i think you must have bind userDropDown in Page_Load event without condition if (!IsPostBack)

Please put dropdown binding part inside if (!IsPostBack) condition then it should work

Sign up to request clarification or add additional context in comments.

Comments

2

Please bind dropdownlist values inside the if(!ispostback){} or after submitting button please bind updated field to dropdownlistname.text

Comments

0

It sounds like you are binding your DropdownList to your datasource at ever request. Instead bind it only if Page.IsPostBack is false like below; (You may not need ObjectDataSource)

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
     //bind your datasource here (something like below)
     userDropDown.DataSource = GetCustomers();
     userDropDown.DataBind();
   }
}

As soon as DataBind() method is called it will lose posted data of that object and the FirstItem will be selected by default.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.