Amit Pal
Amit Pal

Reputation: 11062

How to populate the aspx:Dropdown from c#?

I have a following aspx:dropdown in aspx file:

<asp:DropDownList ID="ddlbStatus" Width="210px" Height="30px" CssClass="ddlb" 
         runat="server" onselectedindexchanged="ddlbStatus_SelectedIndexChanged" Style="text-align:left">
   <asp:ListItem Selected="True" Text="" Value="NA"> </asp:ListItem>
   <asp:ListItem Text="New" Value="NEW"></asp:ListItem>
   <asp:ListItem Text="Open" Value="OPEN"></asp:ListItem>
   <asp:ListItem Text="Closed" Value="CLSD"></asp:ListItem>
</asp:DropDownList>

I want to populate it from my c# file. I tried it with the following code but it didn't work for me:

 ddlbStatus.SelectedItem = r["OrderPeriodStatus"].ToString();

For example r["OrderPeriodStatus"].ToString(); prints NEW or OPEN or CLOSED

I am newbie in asp.net. What i am doing wrong?

Updated

I have already three text present in dropdwonlist. Now what i want , I fetch the status from a SQL Query, and that value will be NEW CLOSED or OPEN. So, for example if i get the CLOSED value from database then in my HTML page CLOSED will be in selected region.

Upvotes: 1

Views: 792

Answers (3)

Priyank Patel
Priyank Patel

Reputation: 7006

You can fill or populate your Dropdownlist in C# in this manner

ddlbStatus.Items.Add(r["OrderPeriodStatus"]);

EDIT:

ddlbStatus.SelectedIndex = ddlbStatus.Items.IndexOf(ddlbStatus.Items.FindByText(r["OrderPeriodStatus"].ToString()));

Upvotes: 2

Coding Flow
Coding Flow

Reputation: 21881

In addition to the other answers you can bind the drop down down list to a datasource that will populate it for you.

ddlStatus.DataSoruce = SomeCollection;
ddlStatus.DataValueField = field1;
ddlStatus.DataTextField = field2;
ddlStatus.DataBind();

Upvotes: 0

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

you can try with

ddlbStatus.Items.Add("test","test");

Or also

ListItem li = new ListItem();
li.Text = "NEW";
li.Value = "NEW";
ddlbStatus.items.add(li);

Upvotes: 3

Related Questions