C# 如何使用文本框的文本声明公共字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9871216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:00:51  来源:igfitidea点击:

how to declare a public string with a textbox's text

c#winformsstringtextbox

提问by Ian Lundberg

i am trying to do

我正在尝试做

      public string str = txtText.Text;

but it wont let me use txtText.txt so how would I declare that so it can be used everywhere?

但它不会让我使用 txtText.txt 那么我将如何声明它以便它可以在任何地方使用?

I can't use it in the button1_click event because if I do it messes it up because I am having a string retrieve from the textbox and set to the textbox so it doesn't work right so I have to have it retrieve the textbox's text somewhere else then set to it.

我不能在 button1_click 事件中使用它,因为如果我这样做会弄乱它,因为我从文本框中检索了一个字符串并将其设置为文本框,所以它不能正常工作,所以我必须让它检索文本框的文本其他地方然后设置它。

采纳答案by Adriano Repetti

Change your declaration to this (I guessyou're trying to make public your TextBox Text property):

将您的声明更改为此(我您正在尝试公开您的 TextBox Text 属性):

public string TextBoxText
{
   get { return txtText.Text; }
   set { txtText.Text = value; }
}

If you simply want to get that value inside your event handler (and inside the same class where your TextBox is declared) then you don't have to use the public specifier in the declaration:

如果您只是想在事件处理程序中(以及在声明 TextBox 的同一类中)获取该值,则不必在声明中使用公共说明符:

string str = txtText.Text;

回答by Arion

You could do it something like this:

你可以这样做:

public partial class Form1 : Form
    {
        public string str;
        public Form1()
        {
            InitializeComponent();
            str=txtText.Text;
        }
     }

回答by Kishore Kumar

Declare a static class and then set your textbox text to it

声明一个静态类,然后将文本框文本设置为它

public static class GlobalClass
{
    public string PropertyName
    {
        get;
        set;
    }
}


private void txtText_TextChanged(object sender, EventArgs e)
{
    GlobalClass.PropertyName=txtText.Text
}

give that in textchange event

在 textchange 事件中给出