C# Label控件问题

问题描述:label控件更新为下一次更大的数字,1到2,2到3,→,逐渐循环。18为最大,到了18再回到1。

img

我更愿意以码为例来说明,先看效果:

img

示例代码如下:

using System;
using System.Windows.Forms;

namespace WindowsFormsApp1.Forms.Demo2
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        // 声明一个当前索引的字段
        private int _currentIndex = 1;
        // 递增的最大值
        private const int MaxIndex = 18;
        private void Form2_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 监听文本框的KeyPress事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 当前键盘输入为回车时
            if (e.KeyChar == 13)
            {
                // 当前索引值加1
                _currentIndex++;
                // 当当前索引值大于最大值是,重置为1
                if (_currentIndex > MaxIndex)
                {
                    _currentIndex = 1;
                }

                label1.Text = $"当前索引值:{_currentIndex}";
            }
        }
    }
}

说明都在注释里,另外,请自行处理你的逻辑。

你定义一个全局变量,让它++,判断它大于18就变成1
这跟label没有一毛钱关系
label只是用来显示的
你愿意用textbox还是gridview都一样

修改textbox的chang事件就实现了