How can I reference a TextBox
object(say textBox1) in another custom class in form1.cs file?
In myclass
, I've written textBox1
, but intelliSense didn't suggest it to me. Changing private to public doesn't solve it.
Here is the sample code of form1.cs
namespace Calculator {
public partial class Form1: Form {
public Form1() {
// InitializeComponent();
}
class myclass {
// What can I do to make texbox1 show up in intelliSense here?
// textBox1
}
public System.Windows.Forms.TextBox textBox1;
}
}
If you want to reference it directly in the scope of myClass
, then declare it as static.
Or you would need an instance of Form1
, but that won't allow you declare a reference to it in the class definition scope, you need to instantiate the instance of Form1
in constructor(or type initializer) that you can assign it to the member of myClass
.
namespace Calculator {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
}
class myclass {
TextBox textBox3=Form1.textBox1;
TextBox textBox4;
Form1 form1;
public myclass() {
form1=new Form1();
textBox4=form1.textBox2;
}
}
static public System.Windows.Forms.TextBox textBox1;
public System.Windows.Forms.TextBox textBox2;
}
}
update:
For the concerning of current instance of Form1
, following is one of the various ways to pass the current instance when instantiate myclass
namespace Calculator {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
textBox1=textBox2; // demonstration for "static make sense"
var x=new Form1.myclass {
form1=this
};
// now x.textBox3 is reference to textBox2
}
public class myclass {
TextBox textBox3=Form1.textBox1;
TextBox textBox4;
internal Form1 form1;
public myclass() {
// form1=new Form1();
textBox4=form1.textBox2;
}
}
static public System.Windows.Forms.TextBox textBox1;
public System.Windows.Forms.TextBox textBox2;
}
}
Nested types have a static relationship to their containing types. That means that by default, they don't have access to any particular instance of the containing type. If you want the inner type to access some field from the containing type, you have to pass an instance to the inner type. The most common way is to pass an instance to the nested type's constructor.
public partial class Form1: Form {
public Form1() {
// InitializeComponent();
}
class myclass {
private Form1 parent;
public myclass(Form1 parent) {
this.parent = parent;
}
public void DoSomething() {
parent.textBox1.Text = "Hello, World!";
}
}
public System.Windows.Forms.TextBox textBox1;
}