Click here to Skip to main content
15,891,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
C#
 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 22:07pm
v2

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.
C#
protected void Page_Load(object sender, EventArgs e)
    { 
       if (!isPostBack)
        {
           ddlCategory.DataSource = DBCategory.GetAllCategory();
           ddlCategory.DataValueField = "CategoryId";
           ddlCategory.DataTextField = "CategoryName";
           ddlCategory.DataBind();
        }
}
 
Share this answer
 
v2
C#
if (!IsPostBack)
{

}
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900