0

textBox1メインフォームにあるコントロールが 1 つありますForm1textBox1別のクラスのテキストを変更できるようにしたいのですが、another_classできません。私には、次のようにして処理another_classするイベントがありますteacherForm1

private void button1_Click(object sender, EventArgs e)
{
    another_class myNew_another_class = new another_class();
    myNew_another_class.teacher(sender, e);
}

したがってanother_class、上記のハンドラーを混乱させて赤いタグを付けてしまうため 、以下を作成することはできません

public another_class (Form1 anytext_Form)
{
    this.anytext_Form = anytext_Form;
} 
4

5 に答える 5

1

次の方法で構文を修正します。

partial class Form1 {
    private void button1_Click(object sender, EventArgs e) {
        another_class myNew_another_class=new another_class(this);
        myNew_another_class.teacher(sender, e);
    }
}

public partial class another_class {
    Form anytext_Form;

    public void teacher(object sender, EventArgs e) {
        // do something
    }

    public another_class(Form anytext_Form) {
        this.anytext_Form=anytext_Form;
    }
}
于 2013-04-03T09:20:04.680 に答える
0

あなたは質問を明確に述べていないと思います。teacherメソッドは何をしていますか?

ただし、他の人が述べたように、すべてのコントロール アクセス修飾子はPrivateであるため、直接アクセスすることはできません。オブジェクトのプロパティでアクセス修飾子を変更するか、プロパティを作成してみてください。

public class Form1 : Form {
    public String TextboxText {
        set { this.myTextbox.Text = value; }
        get { return this.myTextbox.Text; }
    }
}
于 2013-04-03T09:26:23.957 に答える
0

あなたのイベント管理は見栄えがよくないので、実際に何をすべきかを説明する必要があると思います。イベントが役に立たないかもしれませんし、実際に達成したいことを教えてくれればリファクタリングできるかもしれません。

タイトルの質問に答えるために、別のフォームのコントロールはプライベート メンバーであるため、親フォームの範囲外にアクセスすることはできません。あなたができることは、仕事をするパブリックメソッドを公開することです:

public class Form1 : Form
{
    public void SetMyText(string text)
    {
        this.myTextbox.Text = text;
    }
}

public class Form2 : Form
{
    public void Foo()
    {
        var frm1 = new Form1();
        frm1.SetMyText("test");
    }
}
于 2013-04-03T09:20:05.893 に答える
0

これを変える:

another_class myNew_another_class = new another_class();

これに:

another_class myNew_another_class = new another_class(this);
于 2013-04-03T09:20:41.753 に答える
0

これに変更します。

private void button1_Click(object sender, EventArgs e)
{
     another_class myNew_another_class = new another_class(this); //where this is Form1
     myNew_another_class.teacher(sender, e);
}

これは、あなたが持っていた「another_class」のコンストラクターです。

public another_class (Form1 anytext_Form)
{
         this.anytext_Form = anytext_Form;
} 
于 2013-04-03T09:21:21.880 に答える