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>
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.