简体   繁体   中英

setting selected option in asp.net using c#

I have a following code in aspx page

<asp:DropDownList ID="txtSupplierCountry" class="form-control" Width="230px" runat="server">
                    <asp:ListItem Text="Select gender" Value="0"></asp:ListItem>
                    <asp:ListItem Text="male" Value="0"></asp:ListItem>
                    <asp:ListItem Text="female" Value="1"></asp:ListItem>
</asp:DropDownList>

I have a value in database as male/female. I need to set this text using C# code. Basically I am trying to set selected option based on the text from database. I am not getting an idea. I have tried following code but it doesn't work.

String t = "male" // coming from db
txtSupplierCountry.Items.FindByText(t).Selected = true;

when you are saving data Male and Female then why did you keep dropdown values in number like 1,2 etc, change code like this.

<asp:DropDownList ID="txtSupplierCountry" class="form-control" Width="230px" runat="server">
                <asp:ListItem Text="Select Country" Value="0"></asp:ListItem>
                <asp:ListItem Text="male" Value="male"></asp:ListItem>
                <asp:ListItem Text="female" Value="female"></asp:ListItem>

then

txtSupplierCountry.SelectedValue="male";

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