Error when calling a getter from another From
I have two 开发者_开发知识库Froms (Form1, Form2) and I'm getting this Error when I try to call a public function of Form2 from the Form1 class.
Error 1 'System.Windows.Forms.Form' does not contain a definition for 'getText1' and no extension method 'getText1' accepting a first argument of type 'System.Windows.Forms.Form' could be found (are you missing a using directive or an assembly reference?) C:\Users...\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs 24 17 WindowsFormsApplication1.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form gen = new Form2();
gen.ShowDialog();
gen.getText1(); // I'm getting the error here !!!
}
}
public partial class Form2 : Form
{
public string Text1;
public Form2()
{
InitializeComponent();
}
public string getText1()
{
return Text1;
}
public void setText1(string txt)
{
Text1 = txt;
}
private void button1_Click(object sender, EventArgs e)
{
this.setText1(txt1.Text);
this.Close();
}
}
Any ideas? Thanks for your help.
The compile-time type of gen
is currently just Form
. Change that and it should be fine:
Form2 gen = new Form2();
gen.ShowDialog();
gen.getText1();
Note that this has nothing to do with GUIs in particular - it's just normal C#. If you're just starting out with C#, I suggest that you learn it with console apps instead - there are far fewer oddities that way, and you can learn one thing at a time.
I'd recommend that you start following .NET naming conventions, use properties as appropriate, and dispose of forms too:
using (Form2 gen = new Form2())
{
gen.ShowDialog();
string text = gen.Text1;
}
(Even then, Text1
isn't a very descriptive name...)
The problem is that you've declared gen
as the base type Form
, which doesn't have such a method:
private void button1_Click(object sender, EventArgs e)
{
Form gen = new Form2();
gen.ShowDialog();
gen.getText1(); // I'm getting the error here !!!
}
Instead, you need to explicitly define it as type Form2
, or use var
to let the compiler infer the type:
private void button1_Click(object sender, EventArgs e)
{
var gen = new Form2();
gen.ShowDialog();
gen.getText1(); // works fine now
}
Try
Form2 gen = new Form2();
gen.ShowDialog();
gen.getText1();
Hope this help.
精彩评论