0

バインディングにバインディングリストを使用しているグリッドビューがあります。このグリッドでは、アイテムをn回追加/削除できます。したがって、グリッドから行を削除すると、リストから同じアイテムが削除されるという式が必要です。私のリストはBindingListです。

4

2 に答える 2

2

これは、より良いアプローチです。このコードは、選択した行をdataGridおよびbindingListから削除します。

public partial class Form1 : Form
    {
        BindingList<Person> bList;
        public Form1()
        {
            InitializeComponent();
            bList = new BindingList<Person> 
            {
                new Person{ id=1,name="John"},
                new Person{id=2,name="Sara"},
               new Person{id=3,name="Goerge"}
            };
            dataGridView1.DataSource = bList;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string item = dataGridView1[dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex].Value.ToString();
            if (item != null && dataGridView1.CurrentCell.ColumnIndex != 0)
            {
                int _id = Convert.ToInt32(dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value);
                var bList_Temp = bList.Where(w => w.id == _id).ToList();

                //REMOVE WHOLE ROW:
                foreach (Person p in bList_Temp)
                    bList.Remove(p);
            }
        }
    }

    class Person
    {
        public int id { get; set; }
        public string name { get; set; }
    }

ミチャ

于 2011-03-23T18:31:04.587 に答える
0

dataGridがBindingListなどのdataSourceにバインドされている場合は、dataSource(BinidngList内)のアイテムを削除する必要があります。これをチェックしてください:

BindingList bList;

private void buttonRemoveSelected_Click(object sender, EventArgs e)
{
    string item = dataGridView1[dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex].Value.ToString();
    if (item != null)
    {
        int _id = Convert.ToInt32(dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value);
        foreach (Person p in bList)
        {
            if (p.id == _id)
                p.name = "";
        }
    }
}

ミチャ

于 2011-03-23T17:33:10.723 に答える