简体   繁体   中英

c# Listbox and Tabpage

I have 2 Listbox on different tabpages that uses the same datasource

Basically its tabpage1 + listbox1 and tabpage2 + listbox2

I'm trying to do the following :

When I select Item from listbox1 on tabpage1 , I want the same item selected to listbox2 on tabpage2

I tried this:

listbox1.SelectedItem = listBox2.SelectedItem;

also this :

string sitem = "";
sitem = listbox1.SelectedItem.ToString();
listbox2.SelectedItem = sitem

nothing works as expected, I'm wondering if its possible ?

Make sure the tabControl is declared as public or internal . if not then change the tabControl from private to public in the designer.cs file

private System.Windows.Forms.TabControl tabControl1;

public System.Windows.Forms.TabControl tabControl1;

and then

using (Form form = new Form())
{         
     form.listbox1.SelectedItem = form.listBox2.SelectedItem;
}

Finally I made it with the example of PaulF

here is my working code :

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sitem = listBox1.SelectedItem.ToString();
        int index = listBox2.FindString(sitem);
        listBox2.SetSelected(index, true);
    }

so when I select item in listbox1, it also select it in listbox2

Set SelectedIndex property of listbox2 :

listbox1.SelectedIndexChanged += delegate(object sndr, EventArgs args)
{
    var lst = (ListBox) sndr;
    listbox2.SelectedIndex = listbox2.Items.IndexOf(lst.SelectedItem);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM