开发者

Cannot call the controls of another form

i have created a method to clear a textbox in my form1 and i can clear it but when i am calling this method from Form2, the form1 textbox is not clearing. please help me in this.

Form 1:

    private void Clear_Click(object sender, EventArgs e)
    {
        screen_clear();
    }

    p开发者_运维问答ublic void screen_clear()
    {
        MessageBox.Show("Clear");
        textBox1.Text = "";
    }

Form 2:

    private void Clear_Click(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();        
        f1.screen_clear();
        this.Close();
    }

While calling from form2 the "Clear" message gets displayed but the textbox is not clearing.


Form1 f1 = new Form1();

this will create the new instance of form1. this is not running instance of form1 that application creates from Program.cs . You can do this bye the following code

 public  partial class Form1 : Form
 {
    static public Form1 thisForm;

    public Form1()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 a = new Form2();
        a.Show();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        thisForm = this;
    }
}

and in form2 you can call this like

 public partial class Form2 : Form
 {
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        Textbox tb = Form1.thisForm.Controls["textbox1"] as Textbox;
        // Now write you code here
    }

}

Hope this helps


Form1 f1 = new Form1();

You are instantiating a new instance of Form1, not accessing the existing Form1.

In order to access your original form 1 you will have to pass a reference to your original Form1 to your Form2.

For example in form2 you could add this:

    Form1 _masterform;

    void SetMaster(Form MyMaster)
    {
        _masterform = MyMaster;
    }

Then later on you could use Form1.textbox1.clear() or whatnot.

There are other ways of doing this of course, this is just 1 basic way.


MessageBox.Show is a static method - meaning that there's only one, it's global.

When you say Form1 f1 = new Form1(); you are making a new instance of Form1, it's not the Form1 you are looking for.


You can call screen_clear().Because it is public.Check your control textBox1.May be it is not public.So not woriking


You never call f1.show. When Form1 f1 = new Form1() is created a new instance of the form is in memory. THAT is the instance that f1.screen_clear() is invoke on..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜