Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

winforms - How to clear textbox from another form in C#?

I'm trying to clear my textBox from another form in Visual C# when I click a button on another form, but nothing is working. I have done this is VB.Net with ease but in Visual C# I can't do it. Tell me an easy way to do that in (WinForm). I'm using .Net Framework 4.8.

This is my code which I used in VB.Net. Tell me how to do this in C#.

Note: form1 is a form where my textBox1 is present and form2 is a form where my button is present and I want that when I click that button textBox1 text become empty.

form1.textBox1.Text = ""
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Normally, I am working with C on embedded system. I am newbie at OOP and C#. I found 2 solutions Idk they are proper way or not but I hope it solve your problem.

Solution 1:

Go to your WinForm and add the code below to produce a reference to call your Form later

public partial class Form1:Form 
{
    public static Form1 form;
    public Form1()
    {
      form = this;
      InitializeComponent();
    }
}

Now, go to your other Form and try this

Form1.form.textBox1.Clear();

Solution 2:

I tried to use call by ref and it worked. If this method not proper, please inform me with reason.

I added new button with click action to Form1.

private void ButtonClear_Click(object sender, EventArgs e)
{
     class.TextClear(ref textBox1);
} 

And I created new class named "class" and added method below.

public static void TextClear(ref TextBox textBox1)
{
    textBox1.Clear();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...