当datagridview绑定到List <t>时如何删除选定的行

时间:2019-05-15 15:35:59

标签: c# winforms datagridview

我想从datagridview中删除选定的行,并且我的网格已绑定到List<T>。我写了引发错误的代码

  

除非将DataGridView数据绑定到支持更改通知并允许删除的IBindingList,否则无法以编程方式删除行

这是我尝试过的完整示例代码,但是没有用。

public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }

        List<person> _person = null;
        private void Form3_Load(object sender, EventArgs e)
        {
            _person =new List<person>();
            _person.Add(new person { ID = 1, Name = "Tridip" });
            _person.Add(new person { ID = 2, Name = "Sujit" });
            _person.Add(new person { ID = 3, Name = "Arijit" });

            dgLogList.DataSource = _person;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dvr in dgLogList.SelectedRows)
            {
                if (dvr != null)
                {
                    _person.RemoveAt(dvr.Index);
                    dgLogList.DataSource = _person.ToList();
                }
            }

        }
    }

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

因此,请告诉我将datagridview绑定到List<T>时如何从中删除选定的行。

1 个答案:

答案 0 :(得分:0)

不是将DataGridViewRow绑定到您的List,而是将其绑定到BindingSource实例。 BindingSource充当网格和列表之间的中介。还要确保在删除行之后调用Refresh()方法。这是您的代码,包括更新。

public partial class Form1 : Form
{
    private BindingSource _source = new BindingSource();
    List<person> _person = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        _person = new List<person>();
        _person.Add(new person {ID = 1, Name = "Tridip"});
        _person.Add(new person {ID = 2, Name = "Sujit"});
        _person.Add(new person {ID = 3, Name = "Arijit"});
        _source.DataSource = _person;
        dgLogList.DataSource = _source;

    }

    private void Button1_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow dvr in dgLogList.SelectedRows)
        {
            if (dvr != null)
            {
                dgLogList.Rows.Remove(dvr);
                dgLogList.Refresh();
            }
        }
    }
}

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