Display value of DropDownList SelectedItem on a label

Donald Symmons 3,066 Reputation points
2023-10-02T00:25:37.77+00:00

Hello,

I have been trying to show the value of DropDownList selecteditem in a label but all efforts could not yield desired result. I have a table Data as follows:

Id Fruits colors
1 Apple Red
2 Banana Yellow

The Fruits are the items and the values are colors.

The Data in the Fruits column are populated inside a DropDownList items, as shown in the below code. I want it that when user selects a fruit, the value of the SelectedItem in the DropDownList will be attached to a label and be displayed. For example if user selects Banana, then the value will be Yellow and will be attached and displayed in the label.

<asp:UpdatePanel ID="FruitPanel" runat="server" AutoPostBack="true" CssClass="form-control" Font-Size="9pt">                                                 <ContentTemplate>                                                     <asp:Label ID="LabelSymbol" runat="server" Text="Label"></asp:Label>                                                     <div style="margin: 0 auto; padding: 10px; margin-top: 0%;">                                                         <asp:DropDownList ID="DropDownList1" runat="server" CssClass="form-control" Font-Size="10pt" OnSelectedIndexChanged="SelectedIndexChanged">                                                         </asp:DropDownList>                                                     </div>                                                 </ContentTemplate>                                                 <Triggers>                                                     <asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedFruitColor" />                                                 </Triggers>                                             </asp:UpdatePanel>

This below code populates the items from database on to the DropDownList

private void GetFruitColors()         {             string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;             using (SqlConnection con = new SqlConnection(connectionString))             {                 using (SqlCommand cmd = new SqlCommand("SELECT Colors,Fruits FROM FruitTable", con))                 {                     cmd.CommandType = CommandType.Text;                     cmd.Connection = con;                     con.Open();                     DropDownList1.DataSource = cmd.ExecuteReader();                     DropDownList1.DataTextField = "Fruits";                     DropDownList1.DataValueField = "Colors";                     DropDownList1.DataBind();                     con.Close();                 }             }            // DropDownList1.Items.Insert(0, new ListItem("Select your Fruit Colors", "0"));         }

Then I used this code inside SelectedIndexChanged event

protected void SelectedIndexChanged(object sender, EventArgs e)         {             string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;             using (SqlConnection con = new SqlConnection(connectionString))             {                 using (SqlCommand cmd = new SqlCommand("SELECT * FROM Table WHERE Fruits = @Fruits", con))                 {                     cmd.Parameters.AddWithValue("@Fruits", DropDownList1.SelectedItem.Text);                     cmd.CommandType = CommandType.Text;                     cmd.Connection = con;                     con.Open();                     SqlDataReader dr = cmd.ExecuteReader();                     if (dr.Read())                     {                         DropDownList1.SelectedItem.Text = "Fruits";                         DropDownList1.SelectedItem.Value = "Colors";                         if (DropDownList1.SelectedItem.Text == DropDownList1.SelectedItem.Value)                         {                             LabelColors.Text = DropDownList1.SelectedItem.Value.ToString();                         }                     }                     con.Close();                 }             }         }
Developer technologies | .NET | Other
Developer technologies | ASP.NET | Other
Developer technologies | C#
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,191 Reputation points Microsoft External Staff
    2023-10-02T03:51:32.57+00:00

    Hi @Donald Symmons,

    I tested your code and your code contains some minor issues.

    First, the front-end code: Label ID is inconsistent, EventName should be "SelectedIndexChanged", and AutoPostBack="true" needs to be placed in DropDownList.

    Then the backend: In the SelectedIndexChanged event, there is no need to re-bind data from the database and make a judgment about postback in Page_Load.

    Below is the full code. I put the SelectedItem.Text into the label. Then I specify the color of the label based on SelectedItem.Value.

     protected void Page_Load(object sender, EventArgs e)
     {
         if (!IsPostBack)
         {
             GetFruitColors();
         }
     }
     private void GetFruitColors()
     {
         string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString; using (
             SqlConnection con = new SqlConnection(connectionString))
         {
             using (SqlCommand cmd = new SqlCommand("SELECT Colors,Fruits FROM FruitTable", con))
             {
                 cmd.CommandType = CommandType.Text;
                 cmd.Connection = con; con.Open();
                 DropDownList1.DataSource = cmd.ExecuteReader();
                 DropDownList1.DataTextField = "Fruits";
                 DropDownList1.DataValueField = "Colors";
                 DropDownList1.DataBind(); con.Close();
             }
         }
     }
     protected void SelectedIndexChanged(object sender, EventArgs e)
     {
         LabelColors.Text = DropDownList1.SelectedItem.Text.ToString();
         LabelColors.BackColor = System.Drawing.Color.FromName(DropDownList1.SelectedItem.Value.ToString());
    
     }
    
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="FruitPanel" runat="server"  CssClass="form-control" Font-Size="9pt">
            <ContentTemplate>
                <asp:Label ID="LabelColors" runat="server" Text="Label"></asp:Label>
                <div style="margin: 0 auto; padding: 10px; margin-top: 0%;">
                    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" CssClass="form-control" Font-Size="10pt" OnSelectedIndexChanged="SelectedIndexChanged">
                      <asp:ListItem>Choose one</asp:ListItem>
                    </asp:DropDownList>
                </div>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged" />
            </Triggers>
        </asp:UpdatePanel>
    </div>
    

    test1

    Best regards,

    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.