C# - Adding Button inside ListBox

后端 未结 5 488
陌清茗
陌清茗 2021-01-12 15:13

I\'m writing an C# App (WinForm) with a ListBox having content added by the user. Now, I could have a ordinary button under the ListBox to remove items, but I would like to

5条回答
  •  渐次进展
    2021-01-12 15:52

    using System; using System.Collections.Generic; using System.Windows.Forms;

    namespace WindowsFormsApplication11 { public partial class Form1 : Form { List _items = new List();

        public Form1()
        {
            InitializeComponent();
    
            _items.Add("One");
            _items.Add("Two");
            _items.Add("Three");
    
            listBox1.DataSource = _items;
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            // The Add button was clicked.
            _items.Add("New item " + DateTime.Now.Second);
    
            // Change the DataSource.
            listBox1.DataSource = null;
            listBox1.DataSource = _items;
        }
    
        private void button2_Click(object sender, EventArgs e)
        {
            // The Remove button was clicked.
            int selectedIndex = listBox1.SelectedIndex;
    
            try
            {
                // Remove the item in the List.
                _items.RemoveAt(selectedIndex);
            }
            catch
            {
            }
    
            listBox1.DataSource = null;
            listBox1.DataSource = _items;
        }
    }
    

    }

    private void button1_Click(object sender, EventArgs e) { // The Add button was clicked. // ...

    button2.Enabled = true;
    

    }

    private void button2_Click(object sender, EventArgs e) { // The Remove button was clicked. // ....

    if (listBox1.Items.Count == 0)
    {
        button2.Enabled = false;
    }
    

    }

提交回复
热议问题