我有一个gridview,我在其中使用绑定列表进行绑定。在这个网格中,我可以添加/删除项目 n 次。所以我想要表达如果我从网格中删除一行,它将从列表中删除相同的项目。我的列表是 BindingList。
user240141
问问题
9148 次
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,则必须删除数据源中的项目(在 BinidngList 中)。看一下这个:
绑定列表 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 回答