user3291139
user3291139

Reputation: 11

how to put an array elemnts into a selectable list( like dropdown) in asp.net with C# language

I have an array which contains some elements ( it has created dynamically ) I want to put this array elements into a selectable list/drop down menu so user can select options that i want. I tried using selec/option method, but i couldnt set the array elements into the option dynamically. usingasp.net C#

this is my array:

string txt;
txt = Resulttst.Text;
if (txt != "") 
{
    string[] delimiter = { Environment.NewLine };
    string[] ar = txt.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
}

by the way i can show my array elemnts one by one but i want to put them into a selectable list

here is the code which im using in a test mode in my view page tell me which part should i change to show the item1, item2, and so on in the drop down list

<%   string[] arr = { "item1", "item2", "item3" };

 var listItems = arr.Select((r, Index) => new ListItem { Text = r, Value = Index.ToString() });

 DropDownList ddl = new DropDownList();
 ddl.Items.AddRange(listItems.ToArray()); %>


 <form runat="server" >
     <asp:DropDownList ID="ddl"  AutoPostBack="True" runat="server"  >
  </asp:DropDownList> </form>

Upvotes: 0

Views: 2026

Answers (2)

user3291139
user3291139

Reputation: 11

Thanks to HOKBONG to answer my question

after so many trial/errors, ive found the correct code, which i didnt really need to declare a new dropdownlist anymore, because i've already declared it in view mode so the behind code is

//ar is the array
var listItems = ar.Select((r, Index) => new ListItem { Text = r, Value = Index.ToString() });
ddl.Items.AddRange(listItems.ToArray());

and the view code is:

<form runat="server" >
asp:DropDownList ID="ddl" runat="server">
<asp:ListItem Value="plschs"> -->Please choose a username </asp:ListItem>
</asp:DropDownList>
</form>

now the above codes work, it calls the array, and insert the values of the array into the dropdownlist

Upvotes: 0

HOKBONG
HOKBONG

Reputation: 795

I assume you use DropDownList as this is what you tagged on the question: For example your have an array name arr:

        string [] arr = {"item1", "item2", "item3"};

        var listItems =  arr.Select((r, Index) => new ListItem { Text = r, Value = Index.ToString() });

        DropDownList ddl = new DropDownList();
        ddl.Items.AddRange(listItems.ToArray());

Upvotes: 2

Related Questions