m new 2 asp.net.
my prob is after populating the dropdownlist with data from the database wen i select an item it select only the first item.following is my code.where did i go wrong

code:-

con3.start_connection()
dr = con3.executequery("SELECT city_name from City")
DropDownList1.Items.Clear()
While dr.Read
DropDownList1.Items.Add(dr(0))
End While
dr.Close()
con3.close_connection()


dr is the datareader and con3 is the object of the class that makes the connection and runs the query

Recommended Answers

All 4 Replies

put the code in this block :

if(!IsPostBack)
{
// your code goes here
}

Explanation : If you bind data to your dropdownlist, it wont remember its state(example, last selected item before postback)

Hi,
Set AUTOPOSTBACK propery of DROPDOWNLIST to TRUE.

It's because of your IsPostBack method is not active.

You need to add "If Not Page.IsPostBack Then" to the beginning of your code, and "End If" to the end.

The reason for this is that when you click on it and it posts back to the server, the server goes through your entire page and fires off the code again. It will, however, skip over the code that is within the Not Page.IsPostBack.

If you do not have IsPostBack method, then it will always repopulate the dropdownlist. Thus, making it selected index zero, which is the first item in the dropdownlist.

Use IsPostBack to your advantage. You can use it to only execute code when information is sent back to the server on the same page.

Examples:

If Not Page.IsPostBack Then
    response.write("Hi, page loaded for the first time.")
Else
    response.write("The page was sent back to the server, then received again. This is a PostBack.")
End If

Now when a user visits this page, they will see "Hi, page loaded for the first time.", but if you send the page back to the server (like most asp.net server controls do), the page will be rewritten as "The page was sent back to the server, then received again. This is a PostBack.". These are post backs. Play with them, they do wonders!

thanks a lot guys.your suggestions really worked

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.