Click here to Skip to main content
14,447,035 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi All,

I am working asp.net.
i added one dropdownlist and one button to the page. I displayed the item into dropdownlist from database. When i select the item from dropdownlist and clicking on the button it should displaying only the first item from dropdownlist.

Here is my code
 protected void Page_Load(object sender, EventArgs e)
    {
        ddlCategory.DataSource = DBCategory.GetAllCategory();
        ddlCategory.DataValueField = "CategoryId";
        ddlCategory.DataTextField = "CategoryName";
        ddlCategory.DataBind();
}
protected void Search_Click(object sender, EventArgs e)
    {
        int i = ddlCategory.SelectedValue;
}


"i" is displaying first item from the dropdownlist when i select the any item in the dropdownlist..

Please tell me the solution..
Posted
Updated 17-Nov-11 23:07pm
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

What happed is when you clicked on button the Page_load gets called, Which will fill your dropdownlist again and selected item gets reset.

To avoid such behavior, Put PageLoad code in !isPostBack

e.g.
protected void Page_Load(object sender, EventArgs e)
    { 
       if (!isPostBack)
        {
           ddlCategory.DataSource = DBCategory.GetAllCategory();
           ddlCategory.DataValueField = "CategoryId";
           ddlCategory.DataTextField = "CategoryName";
           ddlCategory.DataBind();
        }
}
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 2

if (!IsPostBack)
{

}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100