John Pedro Cocozza
John Pedro Cocozza

Reputation: 1

DropDownList with same "Value" and OnTextChange Event

In an ASP.NET project I have a DropDownList with three values and two of them

must have the same ValueField:

  • "1","Yellow"
  • "1", "Red"
  • "2", "Blue"

The problem is that on the "SelectedIndexChanged" event does not fire when I change from "Yellow" to "Red" because the two options have the same Value.

Is there any way to make an eventRise when I change to "Red" to "Yellow"?

I also tried the TextChanged event, but it rises when both Value and Text change.

Note: I cannot call the event handler from the PageLoad

Upvotes: 0

Views: 942

Answers (1)

VDWWD
VDWWD

Reputation: 35544

The only way is to make the values unique by adding an index: Value="1_0".

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Text="Yellow" Value="1_0"></asp:ListItem>
    <asp:ListItem Text="Red" Value="1_1"></asp:ListItem>
    <asp:ListItem Text="Blue" Value="2_2"></asp:ListItem>
</asp:DropDownList>

Or add them programatically

for (int i = 0; i < DropDownList1.Items.Count; i++)
{
    DropDownList1.Items[i].Value = DropDownList1.Items[i].Value + "_" + i;
}

And then in code behind split the SelectedValue to get the correct color.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Label1.Text = DropDownList1.SelectedValue.Split('_')[0];
}

Upvotes: 1

Related Questions