简体   繁体   English

在C#中,如何使用标签控件在dropdownlist中显示字符串数组?

[英]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. 所以我通过给它分配字符串数组来使用dropdownlist控件。 The coding for it i wrote in Page_Load function. 我在Page_Load函数中编写的代码。

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: 尝试改用SelectedItem属性:

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. 您必须在IsPostBack检查中包装DropDownLists的数据绑定。 Otherwise they will be recreated on PostBack and their selected value will be lost. 否则,它们将在PostBack上重新创建,并且其选择的值将丢失。 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 . 您可以使用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. 也可以这样完成: DdlGender.SelectedItem.Text ,但通常DropDownList是一个KeyValue对,您可以在其中使用值而不是文本。 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 . 在此示例中,他的用户在DropDownList中获得了更多的Text ,但是我们在数据库中不需要该Text ,因此将Values设置为MF

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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