Search code examples
c#numericupdown

Set limit ListBox items by NumericUpDown C#


I'm developing a WinForms application in C# that by an ADD button adds elements to a listBox. What I need to do is set an items limit to this listBox with the NumericUpDown element while the app is running.

So the idea is, I run the app, I select the amount of elements with the NumericUpDown object, and automaticlly set the amount items size limit on my listBox, just allowing add more elements if I up the number with NumericUpDown object. Anyone knows how to do it?

Thank you


Solution

  • Assuming you have button1, numericUpDown1, listBox1, and a TextBox named textBox1 to enter the text to add to the ListBox, following is a full example to demonstrate how you can achieve this. You may make any necessary changes to it to meet your requirements:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
            numericUpDown1.Value = 3;
            numericUpDown1.Validating += NumericUpDown1_Validating;
            button1.Click += Button1_Click;
        }
    
        private void NumericUpDown1_Validating(object sender, CancelEventArgs e)
        {
            if (listBox1.Items.Count > numericUpDown1.Value)
            {
                MessageBox.Show(
                    $"The list already has more than {numericUpDown1.Value} items.");
                e.Cancel = true;
            }
        }
    
        private void Button1_Click(object sender, EventArgs e)
        {
            if (listBox1.Items.Count < numericUpDown1.Value)
            {
                listBox1.Items.Add(textBox1.Text);
            }
            else
            {
                MessageBox.Show(
                    $"The list has reached the limit of {numericUpDown1.Value} items.");
            }
        }
    }
    

    Result:

    Demo