Reputation: 19469
I have a dropdownlist ddlTables
which contains the table names in my database and I display the table contents in the grid based on the table selected.
I am filling the data into my dropdownlist on Page_Load
event using the following code:
ddlTables.Items.Add("-SELECT-");
String getTables = "SELECT TABLE_NAME FROM Information_Schema.Tables where Table_Type = 'BASE TABLE'";
MySqlConnection objMyCon10 = new MySqlConnection(strProvider);
objMyCon10.Open();
MySqlCommand cmd10 = new MySqlCommand(getTables, objMyCon10);
MySqlDataReader r = cmd10.ExecuteReader();
while (r.Read())
{
ddlTables.Items.Add(r[0].ToString());
}
objMyCon10.Close();
When I click Go
button it should display the table contents of the table selected.
But on click of Go
button, I have observed that it first calls the Page_Load
event first and then calls btnGo_Click
.
So it duplicates all the values in my dropdownlist.
Eventually each table name in my dropdownlist list appears twice after I click the Go
button.
How to remove this duplication of the values?
Upvotes: 0
Views: 2081
Reputation: 645
Sample Program
if(!IsPostBack)
{
//Creating Items
ListItem li1 = new ListItem("Male", "1");
ListItem li2 = new ListItem("Female", "2");
ListItem li3 = new ListItem("Secret", "3");
//Adding Items to DropDownList
DropDownList1.Items.Add(li1);
DropDownList1.Items.Add(li2);
DropDownList1.Items.Add(li3);
}
Upvotes: 1
Reputation: 9361
2 options:
If you only need the items to be kept consistent from the point you first visit the page then use:
if(!Page.IsPostback) { /* bind here */ };
If you need the values to be live on very page refresh then disable the viewstate on the control and no previous values will be reapplied to the dropdownlist on postback.
Upvotes: 0
Reputation: 38210
Put your code for filling up the items of the dropdown in a
if(!Page.IsPostback)
{[dropdown filling/binding code here]}
conditional check, this will avoid filling up of the values again when you click on the button and also retain the selection if any made by you in the dropdown
Upvotes: 1
Reputation: 15621
Try putting that code into an
if(!Page.IsPostBack)
{
//your code
}
block
Upvotes: 2