Hello,
I have been trying to attach and display value of DropDownList selected item to a label control but all efforts could not yield desired result.
I have a table Data as follows:
Id | Fruits | Colors |
1 Banana Yellow
2 Orange Green
3 Mango Green
4 Apple Red
The vlaue are the colors while the fruits are the items
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 Orange, then the value of orange which is Green will be attached and displayed in the label control.
HTML
<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="SelectedFruitColor">
</asp:DropDownList>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedFruitColor" />
</Triggers>
</asp:UpdatePanel>
C# This code populates data from database 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"));
}
OnSelectedIndexChange code (C#) is to display the value of the selected item on the label control
protected void SelectedFruitColor(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();
}
}
}