CodeCr
CodeCr

Reputation: 11

listbox selectedindex same value wrong index number

I have same values in listbox. When i click to Index2 (Spain) it selected Index0 (Usa) how can i pass this error?

i must use same values in listbox or alternative control

Thanks.

here is my code;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ListItem li = new ListItem();
            li.Text = "USA";
            li.Value = "06";
            ListItem li2 = new ListItem();
            li2.Text = "ITALY";
            li2.Value = "34";
            ListItem li3 = new ListItem();
            li3.Text = "SPAIN";
            li3.Value = "06";
            ListBox1.Items.Add(li);
            ListBox1.Items.Add(li2);
            ListBox1.Items.Add(li3);

        }

    }
    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Response.Write(ListBox1.SelectedIndex);
    }

Upvotes: 0

Views: 863

Answers (2)

nes
nes

Reputation: 101

If I were you, I would have written such code:

        if (!IsPostBack)
    {
        ListItem li = new ListItem();
        li.Text = "(06) USA";
        li.Value = "01";
        ListItem li2 = new ListItem();
        li2.Text = "(34) ITALY";
        li2.Value = "02";
        ListItem li3 = new ListItem();
        li3.Text = "(06) SPAIN";
        li3.Value = "03";
        ListBox1.Items.Add(li);
        ListBox1.Items.Add(li2);
        ListBox1.Items.Add(li3);

    }

Then I would have gotten the parenthesis part as the value.

PS: I noticed that if you have the same text in your listbox, it returns the smallest SelectedIndex value (such as "John Doe", "Jane Doe", "Mr. Smith", "Jane Doe". In this case, although you click the second Jane Doe, it returns 1. John Doe = 0, Jane Doe = 1, Mr. Smith = 2, Jane Doe = 3). So this answer will be a solution to this problem, too. You can write: "John Doe", "Jane Doe (1)", "Mr. Smith", "Jane Doe (2)" or "John Doe (0)", "Jane Doe (1)", "Mr. Smith (2)", "Jane Doe (3)".

Upvotes: 0

Kramb
Kramb

Reputation: 1092

So the issue is caused by the fact that USA and SPAIN contain the same value. ASP.NET doesn't actually get the selected index of the clicked item in the ListBox. Instead, it uses the value that you selected to determine the index. And because USA and SPAIN have the same value, it chooses the first index that contains that value.

Instead of using Response.Write to get the selected index of the ListItem, I would put a label on the page and set its visibility to false.

Then, in the SelectedIndexChanged event, set the text of the label to the selected index of the ListBox.

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    Label1.Text = ListBox1.SelectedIndex.ToString();
}

Upvotes: 1

Related Questions