4

I am able to bind drop down list with a string array by doing so (not sure whether this is the correct way to implement):

string[] items = { "111", "222", "333" };
ddlSearch.DataSource = items;
ddlSearch.DataBind();

However, what I actually wanted is: When I click the drop down list, the first item showing in the list shall be 111 followed by 222 and 333.

How am I able to add the strings of text to show in the drop down list when I click the drop down list button?

Java has an easy way to add items to be displayed in the list, but how do we do it in C#? (I am very new to C# by the way.)

7
  • By this way. In what order the items are showing in the dropdown? Commented Jan 15, 2015 at 16:53
  • Are you looking to reorder your list? Or are you looking to add additional strings to the list? If you want to add items, it's probably easier to use List<string> or Dictionary<string> Commented Jan 15, 2015 at 16:54
  • I seen several examples of using list, is it possible to populate the drop down list with string array? The order does not matter. For example, I just want "111", "222", "333" in the drop down list. Commented Jan 15, 2015 at 16:56
  • So the question is, how to add to the array? Commented Jan 15, 2015 at 16:57
  • The question is "how to fill up the drop down list with strings" - preferably array of strings Commented Jan 15, 2015 at 16:59

2 Answers 2

11

It would be easier to use List<string>

Markup can be

<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

The backend code would look like

var items = new List<string> {
"111",
"222",
"333"
};
items.Sort(); 

DropDownList1.DataSource = items;
DropDownList1.DataBind();
Sign up to request clarification or add additional context in comments.

Comments

0

Source: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasource.contexttypename(v=vs.110).aspx

public class MovieLibrary
{
    string[] _availableGenres = { "Comedy", "Drama", "Romance" };

    public MovieLibrary()
    {
    }

    public string[] AvailableGenres
    {
        get
        {
            return _availableGenres;
        }
    }
}


<asp:LinqDataSource 
    ContextTypeName="MovieLibrary" 
    TableName="AvailableGenres" 
    ID="LinqDataSource1" 
    runat="server">
</asp:LinqDataSource>
<asp:DropDownList 
    DataSourceID="LinqDataSource1"
    runat="server" 
    ID="DropDownList1">
</asp:DropDownList>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.