C# – 在ListBox中添加Button

我正在编写一个带有ListBox的C#App(WinForm),其中包含用户添加的内容。 现在,我可以在ListBox下面有一个普通的按钮来删除项目,但我希望按钮位于内容旁边,因此位于ListBox内部。

像这样:

  • 内容1 | X
  • 内容2 | X
  • 内容5 | X

问题是我缺乏.NET经验,因此我不知道如何通过所有自动控件继续实现这一点。 我用谷歌搜索了它,但没有得出任何有意义的结果。

任何有关实现此目的的提示,线索或片段都是受欢迎的! 🙂

您可以使用ListView代替ListBox,ListView 可以添加自定义列类型 。

因此,人们可以进行自定义控制,但对于我的应用程序来说,这并不值得。

我所做的是创建一个DataGrid,使其类似于ListView但具有自己的耀斑。 我这样做是因为DataGrid已经在其单元格中内置了一个buttoncontrol。

是的,我知道,有点狡猾的“黑客”,但它就像一个魅力! 🙂

Shay Erlichmen的道具让我想到了我的ListBox。 看看我在那里做了什么? ;)

使用系统; 使用System.Collections.Generic; 使用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){//单击“添加”按钮。 // …

 button2.Enabled = true; 

}

private void button2_Click(object sender,EventArgs e){//单击“删除”按钮。 // ….

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

}

假设它是一个WinForms应用程序

你需要一个自定义控件。 我会查看像http://www.devexpress.com/Products/NET/Controls/WinForms/Editors/editors/ListBoxes.xml这样的供应商,也许有人知道具体做到这一点的控件。

我不知道你为什么要特意做那个? 我会在底部放一个按钮,删除列表框中的所有选定项目。 这被认为是做这种事情的常用方法,除非你想使用jquery并在列表框上放一个onClick事件,如果它存储在数据库中或者从页面上的列表中删除项目,则发送一个调用来删除项目。