简体   繁体   English

DataGridView不允许用户删除行

[英]DataGridView doesn’t allow user to Delete Row

I have a DataGridView as in another question and AllowUserToDeleteRows is set to true . 我有另一个问题中的DataGridView,并且AllowUserToDeleteRows设置为true

The docs say that IBindingList.AllowRemove should also be set to true . 文档IBindingList.AllowRemove也应该设置为true However, a List doesn't seem to have that interface, and it doesn't seem to need it. 但是,列表似乎没有该接口,并且似乎不需要它。 One can remove items from a List. 可以从列表中删除项目。

A similar question's answer suggests setting DataGridView.EditMode to EditOnKeystroke . 一个类似的问题的答案建议将DataGridView.EditMode设置为EditOnKeystroke But that doesn't help. 但这无济于事。

So - How can I get it to allow a user to Delete Rows? 所以-如何获得允许用户删除行的信息?

I was able to delete it with no problem: 我完全可以删除它:

public class MyDataList : List<MyData>
{
    public MyDataList()
    {
        Add(new MyData { ID = 1, Name = "Name 1" });
        Add(new MyData { ID = 2, Name = "Name 2" });
        Add(new MyData { ID = 3, Name = "Name 3" });
        Add(new MyData { ID = 4, Name = "Name 4" });
        Add(new MyData { ID = 5, Name = "Name 5" });
    }
}


public class MyData
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public partial class Form1 : Form
{
    BindingSource myDataListBindingSource;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        myDataListBindingSource = new BindingSource();
        myDataListBindingSource.DataSource = new MyDataList();
        dataGridView1.DataSource = myDataListBindingSource;
    }
}

Result: 结果:

在此处输入图片说明

From what I can see you're using a generic List as a data source to DataGridView. 从我所看到的,您正在使用通用列表作为DataGridView的数据源。 I don't think it is possible to automatically delete rows that way. 我认为不可能以这种方式自动删除行。 You could substitute the List with BindingList and do as the docs say, or have a listener for when user tries to delete the row, set DataSource to null, delete the entry from the list and then assign that list to the datasource again (and possibly invalidate to force DataGridView to be redrawn). 您可以将List替换为BindingList并按文档所述进行操作,或者在用户尝试删除行时使用侦听器,将DataSource设置为null,从列表中删除条目,然后将该列表再次分配给数据源(可能还可以)无效以强制重绘DataGridView)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM