Reynier
Reynier

Reputation: 2478

Clear var defined in UserControl from main Form

I've a UserControl where I define some vars and also has some components like buttons, textbox and some others:

private List<string> bd = new List<string>();
private List<string> bl = new List<string>();

It's possible to access to those vars from namespace WindowsFormsApplication1? How? If I try to do this from private void recuperarOriginalesToolStripMenuItem_Click(object sender, EventArgs e) I got a error:

bl = new List<string>();
blYear.Enabled = true;
btnCargarExcel.Enabled = true;
filePath.Text = "";
nrosProcesados.Text = "";
executiontime.Text = "";
listBox1.DataSource = null;

What's the right way to do this?

EDIT: clarify What I'm looking for is to clean values each time I access a menu item. For textBox and others components it works thanks to the suggestions made here but for List I don't know how to set it to null

Upvotes: 0

Views: 164

Answers (2)

user2354869
user2354869

Reputation:

you can always access any variable that you define, any control that you place on your UserControl at all those places, where you have placed your UserControl.

Just make sure, you have made your variables public and exposed your Controls through public properties i.e

suppose you have kept a TextBox on your UserControl for Names. In order to use it outside, you must expose it through a public property

public partial class myUserControl:UserControl
{
   public TextBox TxtName{ get{ return txtBox1;}}

   public ListBox CustomListBoxName
   {
      get
      {
         return ListBox1;
      }
      set
      {
         ListBox1 = value;
      }
   }

   public List<object> DataSource {get;set;}

} 

and you can use it on the form you have dragged this usercontrol i.e.

public partial form1: System.Windows.Forms.Form
{
   public form1()
   {
       InitializeComponent();
       MessageBox.Show(myUserControl1.TxtName.Text);

       MessageBox.Show(myUserControl1.CustomListBoxName.Items.Count);
       myUserControl1.DataSource = null;   
   }
}

similary you can expose your variables, through public properties. That way you can also control whether you want some of your variables to be readonly or what!

Upvotes: 1

Kenneth
Kenneth

Reputation: 28737

You need to expose a property and then access that property on the usercontrol-instance from your main form:

UserControl

public List<string> BD {get; set;}

Main form

MyUserControl.BD = new List<string>();

Upvotes: 1

Related Questions