【问题标题】:How to delete item from the BindingList , binded with gridview?如何从与 gridview 绑定的 BindingList 中删除项目?
【发布时间】:2011-03-23 17:16:48
【问题描述】:

我有一个gridview,我在其中使用绑定列表进行绑定。在这个网格中,我可以添加/删除项目 n 次。所以我想要表达如果我从网格中删除一行,它将从列表中删除相同的项目。我的列表是 BindingList。

【问题讨论】:

    标签: c# list data-binding bindinglist


    【解决方案1】:

    这是一种更好的方法。该代码从 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; }
        }
    

    米加

    【讨论】:

      【解决方案2】:

      如果您的 dataGrid 绑定到数据源,如 BindingList,则必须删除数据源中的项目(在 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 = "";
              }
          }
      }
      

      米加

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-17
        • 1970-01-01
        • 2010-10-12
        • 1970-01-01
        相关资源
        最近更新 更多