Hi guys as the title says i want to delete all rows from a datagridview and in the process deleting them from the database. Heres my code but its only deleting one row and not all. Thank you
private void clear_Click(object sender, EventArgs e)
{
if (this.dgvProducts.SelectedRows.Count > 0)
{
foreach (DataGridViewRow row in dgvProducts.SelectedRows)
{
int selectedIndex = dgvProducts.SelectedRows[0].Index;
int rowID = int.Parse(dgvProducts[0, selectedIndex].Value.ToString());
crud.AddRecord("Delete from Supplier_productlist where ProductID = '" + rowID + "' and SupplierID = '"+supplierid.Text+"' ");
}
}
//dgvProducts.Refresh();
}
It seems that in the foreach loop, only 0th item was processed.
If you want to specify index, I would suggest for loop instead of foreach.
If you want to use foreach, then you probably should work on "row" itself instead of keep working on 0th item:
dgvProducts.SelectedRows[0]
dgvProducts[0, selectedIndex]
In your code, you're looping over only SelectedRows , not all Rows .
foreach (DataGridViewRow row in dgvProducts.SelectedRows)
To loop over the whole datagrid's rows you should use
foreach (DataGridViewRow row in dgvProducts.**Rows**)
Hope, this link helps: https://msdn.microsoft.com/ru-ru/library/system.windows.forms.datagridview.rows(v=vs.110).aspx
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.