C# - Adding Button inside ListBox

倖福魔咒の 提交于 2019-12-01 04:57:42

Instead of ListBox you can use ListView, ListView has the ability to add custom column types.

So one could make a custom control but for my app it isn't really worth the trouble.

What I did was to create a DataGrid, made it resemble a ListView but with its own flare. I did this because the DataGrid already has a buttoncontrol built in to its cells.

Yes I know, kind of fugly "hack", but it works like a charm! :)

Props to Shay Erlichmen who led me into thinking outsite my ListBox. See what I did there? ;)

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;
}

}

Assuming it's a WinForms app

You'd need a custom control for that. I would check around vendors like http://www.devexpress.com/Products/NET/Controls/WinForms/Editors/editors/ListBoxes.xml maybe someone knows of a control that specifically does that.

I don't know why you would want to do specifically that? I would put a button at the bottom that deletes any selected items in the listbox. That is deemed the usual way of doing such a thing unless you want to use jquery and put an onClick event on the listbox that sends a call to delete the item if it is stored in a database or remove the item from the list on the page.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!