简体   繁体   中英

After removing an element from binded list and select a row in DataGridView, that row is deleted too in Winforms C#

I know that title is too long, I will explain the situation: I have data grid view binded to a list:

BindingList<MyViewModel> _list = new BindingList<MyViewModel>
{
    new MyViewModel{ Num =1 , Val ="test"},
    new MyViewModel{ Num =2 , Val ="test1"},
    new MyViewModel{ Num =3 , Val ="test2"},
};

dataGridView1.DataSource = _list;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;

and I binded event to listen to Delete command:

 dataGridView1.KeyDown += (s, ev) =>
        {
            if (ev.KeyCode == Keys.Delete)
            {
                var item = dataGridView1.SelectedRows[0].DataBoundItem as MyViewModel;

                if (item != null)
                {
                    _list.Remove(item);

                    dataGridView1.Rows[0].Selected = true;
                }
            }
        };

and view model looks like:

public sealed class MyViewModel
{
    public string Val { get; set; }

    public int Num { get; set; }
}

In grid I will have 3 items: if I delete item 3, the item 2 is deleted too (or hidden maybe)

Why ?

After delete an item, I want to select first item from data grid dataGridView1.Rows[0].Selected = true; .

If I remove dataGridView1.Rows[0].Selected = true; then is fine, item 2 is visible.

You need to tell the form engine (and the DataGridView) that you have handled that KeyDown event, otherwise it (the DataGridView) will receive the key and do its default thing (delete a row)

dataGridView1.KeyDown += (s, ev) =>
{
    if (ev.KeyCode == Keys.Delete)
    {
        var item = dataGridView1.SelectedRows[0].DataBoundItem as MyViewModel;

        if (item != null)
        {
            _list.Remove(item);

            dataGridView1.Rows[0].Selected = true;
            ev.Handled = true;
        }
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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