How to take the value of a Listbox from the selected index of another Listbox?

Asked

Viewed 8,812 times

3

I’m trying to get the value of a ListBox from the selected index of another ListBox, but it doesn’t work. What I have so far:

for (int i = 0; i < 10; i++)
{
    Lst_ListBoxA.Add(2 * (3 * i) * 4);
    Lst_ListBoxB.Add(2 * (3 / i) * 4);
}
private void Lst_ListBoxB_SelectedIndexChanged(object sender, EventArgs e)
{
    //Aqui, o usuário seleciona o segundo índice (1).
    string Valor = Lst_ListBoxA.GetItemText(Lst_ListBoxB.SelectedIndex);
    MessageBox.Show(valor);
}

What is being returned, or shown in Messagebox, is the selected index of Lst_ListBoxB, 1, and not the corresponding index value of Lst_ListBoxA, 24, what would be the right way to do it?

  • Webforms or Windows Forms?

  • 1

    I edited the tags, winforms.

2 answers

3


You must be looking for something like this:

private void Form1_Load(object sender, EventArgs e)
{
   Lst_ListBoxA.Items.Add("Item 1A");
   Lst_ListBoxA.Items.Add("Item 1B");
   Lst_ListBoxA.Items.Add("Item 1C");

   Lst_ListBoxB.Items.Add("Item 2A");
   Lst_ListBoxB.Items.Add("Item 2B");
   Lst_ListBoxB.Items.Add("Item 2C");
}

private void Lst_ListBoxB_SelectedIndexChanged(object sender, EventArgs e)
{
   int i = Lst_ListBoxB.SelectedIndex;
   string Valor = Lst_ListBoxA.Items[i].ToString();
   MessageBox.Show(Valor);
}

This should work for you.

  • Then it is possible to treat any object that has a collection of items (Combobox, Listbox, Listview...) as if it were an array?

2

For the event SelectedIndexChanged, you can catch the Index of ListBox.

private void Form1_Load(object sender, EventArgs e)
{
        listBox1.Items.Add("aluno 1");
        listBox1.Items.Add("aluno 2");
        listBox1.Items.Add("aluno 3");

        listBox2.Items.Add("aluno 1");
        listBox2.Items.Add("aluno 2");
        listBox2.Items.Add("aluno 3");     
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
        int i = listBox1.SelectedIndex; //pegando o index do item selecionado
        listBox2.SelectedIndex = i; //posicionando o outro listbox
        MessageBox.Show(listBox2.Text); //mostrando o valor que ele tá!
}

In this example loading the listbox works like this.

Reference

  • 1

    I did not quite understand the last line... I will put more data in the question.

  • @Patrick, it’s this way usually by the event! I click it already positions and shows the value!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.