c# - 在 WinForm 中声明一个全局整数

标签 c# winforms textbox int global

我正在尝试声明 int

 private int i = 15 - textBox1.Text.Length;

作为此代码的全局整数

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBox1.Checked == true)
        {
            i = 15 - textBox1.Text.Length;
            timer1.Enabled = true;
            timer1.Start();
        }
        else
        {
            timer1.Enabled = false;
        }
    }
    private int i = 15 - textBox1.Text.Length; //this wont work but i need it to
    private int y = 15 - textBox1.Text.Length; //this wont work either but i also need it to
    private void timer1_Tick(object sender, EventArgs e)
    {

        if (i <= 11)
        {
            i++;
            string ping = new string(' ', i) + textBox1.Text;
            label1.Text = ping;
            if (i == 10)
            {
                y = 11;
            }
        }
        else if (y > 0)
        {
            y--;
            string pong = new string(' ', y) + textBox1.Text;
            label1.Text = pong;
            if (y == 0)
            {
                i = 0;
            }
        }
    }

但是我得到了错误

字段初始值设定项不能引用非静态字段、方法或属性“text_test.Form1.textBox1”

帮助?

最佳答案

您正在尝试设置变量 iinitial 值(顺便说一下,这是一个错误的变量名——变量名应该是描述性的!) .

您需要在工作流程的某个时刻设置 i 的值——在没有任何上下文的情况下,我猜可能是在 OnTextChange 事件或其他事件中类似。

关于c# - 在 WinForm 中声明一个全局整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9287805/

相关文章:

reporting-services - 如何在表达式中引用文本框值? SSRS

testing - 使用带有元素 by.id Protractor 测试错误的输入框

c# - itextsharp document.close 上的堆栈溢出异常

c# - 是否可以将 DirectX 的单个全屏页面添加到 XAML/C# Windows 8 商店应用程序?

c# - 如何显式转换类型为 'object' 的变量以满足多类型泛型约束?

javascript - 将文本字段限制为仅数字的最佳方法?

c# 将 var 声明为接口(interface)。为什么这可能?

winforms - 你如何处理 Winforms 中临时无用的控件(隐藏与禁用)?

c# - NumericUpDown 控件可以做到这一点吗?

winforms - 如何从事件处理函数中退出 Windows 窗体应用程序?