简体   繁体   中英

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.

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);

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()));

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM