How do I get the value of a ListBox from the selected index of another ListBox?

3

I'm trying to get the value of a ListBox from the selected index of another ListBox , but it does not work. What I have until the present moment:

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 the MessageBox , is the selected index of Lst_ListBoxB , 1 , not the corresponding index value of Lst_ListBoxA , 24 , what would be the correct way to do it?

    
asked by anonymous 26.05.2014 / 02:07

2 answers

3

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

    
26.05.2014 / 02:37
2

By event SelectedIndexChanged , you can get the Index from 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

26.05.2014 / 02:21