How to delete item from the BindingList , binded with gridview?
I have a gridview where i am using a binding list for binding. In this grid i can add/remove item n times. So i want expression that if i delete a row from grid, it will delete the same item from the list. M开发者_开发技巧y List is BindingList.
This is a way better approach. The code removes the selected row from dataGrid and from 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; }
}
Mitja
If your dataGrid is bound to a dataSource, like BindingList, you have to delete the item in the dataSource (in BinidngList). Check this out:
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 = "";
}
}
}
Mitja
精彩评论