Accessing an object on userControl from another us

2019-07-24 18:39发布

问题:

I have this userControl which contains ListBox. I want to access that ListBox from another userControl.

For example:

UserControl1.ListBox1.Items.Count;

回答1:

Add A Public Property ItemsCount in your user control

public int ItemsCount 
{
    get { return ListBox1.Items.Count; }
}

or

public ListBox MyListBox 
{
    get { return ListBox1; }
}

to access the whole listbox



回答2:

Make a property of ListBox in your first usercontrol and get that like

public ListBox lstBox
{
  get { return this.listBox1;}
}

Now access the ListBox from other usercontrol like that

usercontrol1 obj = new usercontrol1();
int itemCount =  obj.lstBox.Items.Count ;


标签: c# object static