下拉列表所选项目不显示在消息框中

问题描述:

大家好,

我正在asp.net.
我在页面上添加了一个下拉列表和一个按钮.我将项目显示到数据库的下拉列表中.当我从下拉列表中选择项目并单击按钮时,它应该仅显示下拉列表中的第一项.

这是我的代码

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"将显示下拉列表中的第一项..

请告诉我解决方案..



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

Please tell me the solution..

单击按钮时,调用的是Page_load,这将再次填充您的下拉列表,并且重置选定的项目.

为避免这种情况,请将PageLoad代码放入!isPostBack

例如
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();
        }
}


if (!IsPostBack)
{

}