简体   繁体   中英

in c#, how to display array of string in dropdownlist using label control?

So i'm using dropdownlist control by assigning array of string to it. The coding for it i wrote in Page_Load function.

protected void Page_Load(object sender, EventArgs e)
{
    string[] Gender = { "Male", "Female" };
    DdlGender.DataSource = Gender;
    DdlGender.DataBind();

    string[] Update = { "Yes", "No" };
    DdlUpdates.DataSource = Update;
    DdlUpdates.DataBind();
}

and now i want to know how to display the selected string accurately in the dropdownlist after i pressed the button?

Also i'm using this coding to display, it would only display the first string when i selected the second string in the dropdownlist...

protected void BtnSubmit_Click(object sender, EventArgs e)
{
    int i;

    lblGender.Text = DdlGender.Text;
    lblUpdates.Text = DdlUpdates.Text;
}

Try use SelectedItem property instead:

protected void BtnSubmit_Click(object sender, EventArgs e)
{ 
   lblGender.Text = DdlGender.SelectedItem.ToString();
   lblUpdates.Text =  DdlUpdates.SelectedItem.ToString();
}

You have to wrap the databinding of the DropDownLists in a IsPostBack check. Otherwise they will be recreated on PostBack and their selected value will be lost. That is why you always get the first string.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        string[] Gender = { "Male", "Female" };
        DdlGender.DataSource = Gender;
        DdlGender.DataBind();

        string[] Update = { "Yes", "No" };
        DdlUpdates.DataSource = Update;
        DdlUpdates.DataBind();
    }
}

And you can get the values on the button click with SelectedValue .

DdlUpdates.Text = DdlGender.SelectedValue;
DdlUpdates.Text = DdlUpdates.SelectedValue;

It can also be done like this: DdlGender.SelectedItem.Text , but usually a DropDownList is a KeyValue pair where you use the value, not the text. Here an example.

<asp:DropDownList ID="DdlGender" runat="server">
    <asp:ListItem Text="I'm a male" Value="M"></asp:ListItem>
    <asp:ListItem Text="I'm a female" Value="F"></asp:ListItem>
</asp:DropDownList>

In this examplet he user gets a lot more Text in the DropDownList, but we don't need that in the database, so we set the Values to just M and F .

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