0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!!
1

Try use SelectedItem property instead:

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

1 Comment

Thanks! I will keep in mind about the selecteditem and text in the future

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.