How to remove rows from DataGridView?

旧时模样 提交于 2021-01-19 17:32:54

问题


I have a winform with preloaded DataGridView over it...I want to remove rows from datagridview on selecting or highlighting the rows and clicking over the button...

Also want to clear all the columns....

Currently i used

foreach (DataGridViewRow dgvr in dataGridView2.Rows)
{
    if (dgvr.Selected == true)
    {
        dataGridView2.Rows.Remove(dgvr);
    }
}

but it is throwing an exception that "rows or not commited" or something....it would be appreciable if any one have any better suggestions....


回答1:


If you have AllowUserToAddRows enabled on your DataGridView then you might be accidently deleting the empty row at the bottom of the DataView which is a placeholder for the next user created row. Try disabling this option if not required, otherwise try using code like this:

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
    if(!row.IsNewRow)
       dataGridView1.Rows.Remove(row);
}


来源:https://stackoverflow.com/questions/11258478/how-to-remove-rows-from-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!