简体   繁体   中英

How to empty the current row of a DataGridView in C#?

I am developing a windows form application for a Books Store. In this application have a datagridview to select books for sale. If there are no items available in the stock I need to clear the current row values.So how can I do this. I tried this

dataGridView1.Rows.Clear();

But this clear entire datagridview. But I need to clear only current row when I click ok the message.

在此处输入图片说明

You will need to specify the row in the datagrid that you want to delete. You can do this by selecting the "index" of the row which is selected.

dataGrid.Rows[index].Selected = true;

or you could do the following:

dataGrid.SelectedRows.Clear();
foreach(DataGridViewRow row in dataGrid.Rows)
{
    if(YOUR CONDITION)
       row.Selected = true;
}

I always use removeat by first checking to ensure something is selected and then do a removeat while passing the index.

if(dataGridView1.CurrentRow.Index > -1 && !dataGridView1.Rows[dataGridView1.CurrentRow.Index].IsNewRow)
    dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);

EDIT: Added a check for IsNewRow in case AllowUsersToAddRows is True which would throw and exception if that was the selected row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM