Saeid
Saeid

Reputation: 2036

Populating a DropDownList

I want to fill a drop-down list each time with a link button(Edit) like this: enter image description here

And I used this code to fill it:

sqlcmd1 = new SqlCommand(@"SELECT country FROM Authors  
                           WHERE AuthorID=@AuthorID 
                           AND AuthorUserName=@AuthorUserName", sqlconn);
sqlcmd1.Parameters.AddWithValue("@AuthorUserName", AuthorUserName);
sqlcmd1.Parameters.AddWithValue("@AuthorID", AuthorID);

dd_country.Text= ((string)sqlcmd.ExecuteScalar()).ToString();

But it fills the drop down list with a number!

If I change the code to the below something else happens:

dd_country.SelectedItem.Text= ((string)sqlcmd.ExecuteScalar()).ToString();

It caused changing the dropdownlist item to a selected item; for example it changed Canada to Burundi! In fact the items only changed temporarily and I then have two Canada items in the drop down list!

enter image description here

How can I fill the dropdownlist by edit button without these problems?

Upvotes: 2

Views: 228

Answers (1)

Aniket Inge
Aniket Inge

Reputation: 25695

You must set the Value of the drop-down list to the number, and the Text to the country name.

Then you can do this to set it as selected -> dropdownlist.SelectedValue=1 and it will select the country appropriately.

Avoid this problem using Data-Source like so:

enter image description here

A dialog box pops up that looks like this:

enter image description here

And you can follow on :-) from there

Upvotes: 2

Related Questions