简体   繁体   中英

Populating the dropdownlist from database

I have a drop downlist control and a button control in my asp.net web page. I'm populating my drop down list from data base.

I Have this method to populate the drop down list.

     public void fillDD()
{
    SqlDataReader rd = new ViewBorrowersOP().getTitlestoCombo();
    while (rd.Read())
    {
        DDTitle.Items.Add((String)rd[0]);
    }
}

This is my business layer. Method for that.

     public SqlDataReader getTitlestoCombo()
{
    string query1 = "EXEC getAllBKTitles";
    return new DataAccessLayer().executeQuerys(query1);
}

I'm calling the method in page load event.

 protected void Page_Load(object sender, EventArgs e)
{
    fillDD();
}

I'm clicking button to populate a data grid. It works fine. And the code to populate the drop downlist works fine too. But each time When I click button to populate grid view or each time I refresh the Page the dropdown list is populating again with same items.

   Let's say for the first time when I load the page the drop down list is populated with following items. 


    CAT
    DOG 
    BAT

If I click the button or if the page reloads it will again populate ,when this happens three times my drop down list looks like this.

    CAT
    DOG 
    BAT
    CAT
    DOG 
    BAT
    CAT
    DOG 
    BAT

How to prevent this happening?

Replace the below with

 protected void Page_Load(object sender, EventArgs e)
    {
        fillDD();
    }

with

protected void Page_Load(object sender, EventArgs e)
{
   if(!IsPostBack)
   {
    fillDD();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM