简体   繁体   English

C#列表框和标签页

[英]c# Listbox and Tabpage

I have 2 Listbox on different tabpages that uses the same datasource 我在使用相同数据源的不同选项卡页上有2个列表框

Basically its tabpage1 + listbox1 and tabpage2 + listbox2 基本上它的tabpage1 + listbox1和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 当我从tabpage1的listbox1中选择项目时,我希望在tabpage2的listbox2中选择相同的项目

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 . 确保tabControl声明为publicinternal if not then change the tabControl from private to public in the designer.cs file 如果不是,则将designer.cs文件中的tabControl从private更改为public

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 最后,我以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 所以当我在listbox1中选择项目时,也会在listbox2中选择它

Set SelectedIndex property of listbox2 : 设置listbox2 SelectedIndex属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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