如何删除dataGridView1中未绑定的数据行
本文关键字:绑定 数据 dataGridView1 何删除 删除 | 更新日期: 2023-09-27 18:13:31
我想从dataGridView1中删除未绑定的数据行?我编写了以下代码
private void deleteButton1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
dataGridView1.Rows.Remove(row);
}
}
但是它不起作用。请建议我一些帮助代码。提前感谢
在IDE模式下非常简单。只需在FullRowSelect属性设置 Datagridview的SelectionMode,并在运行时只需按Delete键在任何选定的行你想要的。它会被删除
或
试试下面的按钮点击事件:
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
}
欢呼
我认为您可能不应该在枚举它时更改dataGrid中的行集合。您可以首先通过dataGirdView1枚举。SelectedRows集合获取行以删除索引,然后实际删除它。例如:
private void deleteButton1_Click(object sender, EventArgs e)
{
// collect deleting row indexes
List<int> deletingRowIndexes = new List<int>();
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
deletingRowIndexes.Add(row.Index);
}
// sort indexes
deletingRowIndexes.Sort();
// remove rows in backward order to save rows indexes
for(int i = deletingRowIndexes.Count - 1; i>=0; i--)
dataGridView1.Rows.RemoveAt(deletingRowIndexes[i]);
}
您可以这样尝试....
foreach (DataGridViewRow row in dataGridView1.Rows)
{
// invert row selections
if (!row.Selected)
{
if (!row.IsNewRow)
{
row.Selected = true;
}
}
else
{
row.Selected = false;
}
}
// remove selected rows
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
dataGridView1.Rows.Remove(row);
}
}
代码应该工作,尝试在foreach循环后添加dataGridView1.Refresh();
。我测试过了,效果不错。SelectedRows
是只删除DgridView中选定的行
public Form1()
{
InitializeComponent();
dataGridView1.Columns.Add("ColumnA", "ColumnA");
dataGridView1.Columns.Add("ColumnB", "ColumnB");
dataGridView1.Rows.Add(new[] {"1colA", "1colB"});
dataGridView1.Rows.Add(new[] { "2colA", "2colB" });
}
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
dataGridView1.Rows.Remove(row);
}
dataGridView1.Invalidate();
}