【问题标题】:Disable a button in c# under a condition在条件下禁用c#中的按钮
【发布时间】:2013-01-27 11:50:58
【问题描述】:

所以,我有这个数组,它可以按一个按钮一个一个地添加元素,它会通过以下方式添加元素: arreglo.Add(textBox1.Text.ToString());

我只想将它可以添加到数组中的元素数量限制为 10。它最多可以有 10 个元素,不能再多了。我该怎么做?

如果有帮助,这些是我认为可以提供帮助的代码部分:

ArrayList arreglo;
    public Form1()
    {
        InitializeComponent();
        arreglo = new ArrayList();
    }

        private void button5_Click(object sender, EventArgs e)
    {
        //Agregar
        arreglo.Add(textBox1.Text.ToString());
        /*if (arreglo.Count > 10)
        {
            listBox1.Items.Add("No more than ten elements");
        }*/
        this.textBox1.Clear();
        this.textBox1.Focus();
    }

顺便说一句,我还需要对该数组进行一些计算,但我已经涵盖了。

【问题讨论】:

  • 您希望禁用按钮或限制数组长度?
  • @mihirj 一旦达到数组的限制,我想禁用一个按钮。
  • 请查看以下答案是否适合您的情况

标签: c# arrays button arraylist listbox


【解决方案1】:

你可以简单地解决这个问题:

private void button5_Click(object sender, EventArgs e)
    {
        //Agregar
        arreglo.Add(textBox1.Text.ToString());
        if (arreglo.Count > 10)
        {
            button5.Enabled = false;
        }
        this.textBox1.Clear();
        this.textBox1.Focus();
    }

【讨论】:

  • 如果这解决了你的问题,你能把它标记为答案吗?
  • 实际上,我用这两个问题作为答案。但这对我帮助最大,所以会这样。
【解决方案2】:

这是一种更改数组容量的方法,在这种情况下,数组可以从 0 到 9(10 个元素)

class Program
{
    static void Main(string[] args)
    {
        ArrayList list = new ArrayList();
        for(int i = 1; i < 20; i++)
        {
            try
            {
                list.Capacity = 9;
            }
            catch (Exception)
            { button5.Enabled = false; }
            list.Add("teststring");
        }
        list = list;
    }
}

【讨论】:

    【解决方案3】:

    在添加数组有多少元素后检查并将Button启用属性设置为false - 它会禁用按钮。

    private void button5_Click(object sender, EventArgs e)
    {
       arreglo.Add(textBox1.Text.ToString());
       this.textBox1.Focus();       
       this.textBox1.Clear();   
    
       if (arreglo.Count >= 10)
       {
           button5.Enabled = false;
       }
    }
    

    【讨论】:

    • 感谢您的宝贵时间,但我已经有了答案。谢谢!
    【解决方案4】:

    为什么是ArrayList?你的目的是什么?

        private void button10_Click(object sender, EventArgs e)
        {
            if (arreglo.Count < 10)
            {
                arreglo.Add(textBox1.Text);
                this.textBox1.Clear();
                this.textBox1.Focus();
            }
            else
                button10.Enable = false;
        }
    

    【讨论】:

    • 感谢您的宝贵时间,但我已经涵盖了。再次感谢!
    • 欢迎,如果您认为该答案对您有用,您可以投票,如果该答案最适合您,您可以接受 answer ..欢迎来到stackoveflow :D
    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 2021-09-28
    相关资源
    最近更新 更多