我可以在同一时间调用我的方法并使用textbox1.text吗? [英] Hod do I call my method and use textbox1.text in the same time?

查看:91
本文介绍了我可以在同一时间调用我的方法并使用textbox1.text吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的格式是:

I have this in my form :

private void button1_Click(object sender, EventArgs e)
       {
           RecordAndRead.Record();
       }





这个在另一个班级:



and this in another class:

public static void Record()
         {
             const string filePath= @"../../Notes.txt";

             using (StreamWriter record=new StreamWriter(filePath,true))
             {
                 string UserInput = textBox1.Text;
                 record.WriteLine(UserInput);
                 textBox1.Text = null;
                 System.Windows.Forms.MessageBox.Show("Your information has been saved");
             }
         }





我不能使用我的方法,如果它不是静态的,但是当它是我无法访问textBo1.Text。

如何修复它?



我尝试过:



我在Record方法中从public static void和public void返回堡垒,但它不能解决这两个问题。



I can't use my method if it is not static,but when it is I can't access textBo1.Text.
How can I fix it?

What I have tried:

I go back and fort from public static void and public void on my Record method, but it does not fix both.

推荐答案

如果它在不同的类中,那么你无法访问文本框,因为它是Form类的非静态(或实例)成员,所以你需要正确的表单实例来无论如何都要访问它。相反,通过方法参数将数据传递给其他类:

If it's in a different class, then you can't access the textbox anyway as it's a non-static (or instance) member of your Form class, so you need the right instance of the form to access it anyway. Instead, pass the data to your other class via a method parameter:
public static string Record(string text)
    {
    const string filePath= @"../../Notes.txt";
    using (StreamWriter record=new StreamWriter(filePath,true))
        {
        string UserInput = text;
        record.WriteLine(UserInput);
        System.Windows.Forms.MessageBox.Show("Your information has been saved");
        text = null;
        }
    return text;
    }

然后在调用时传递数据:

Then pass it the data when you call it:

private void button1_Click(object sender, EventArgs e)
    {
    textBox1.Text = RecordAndRead.Record(textBox1.Text);
    }


这篇关于我可以在同一时间调用我的方法并使用textbox1.text吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆