c# - How to delete a selected row from datagridview? -
if (dgvproductcatalog.rows.count > 1 && dgvproductcatalog.selectedrows[0].index != dgvproductcatalog.rows.count - 1) { cmd = new sqlcommand("delete products productid= " + dgvproductcatalog.selectedrows[0].cells[0].value.tostring() + " " , connection); try { connection.open(); cmd.executenonquery(); } catch (sqlexception ex) { messagebox.show(ex.message); } { connection.close(); dgvproductcatalog.rows.removeat(dgvproductcatalog.selectedrows[0].index); messagebox.show("record deleted successfully!"); displaydata(); cleardata(); } }
i using above piece of code on button click delete selected row getting "system.argumentoutofrangeexception: index out of range. must non-negative , less size of collection." doing wrong here?
thanks!
i use currentrow instead
dgvproductcatalog.currentrow.cells[0].value
then
dgvproductcatalog.rows.removeat(dgvproductcatalog.currentrow.index)
or
dgvproductcatalog.rows.removeat(dgvproductcatalog.selectedcells[0].rowindex)
also while @ it, change line too
if (dgvproductcatalog.rows.count > 1 && dgvproductcatalog.selectedcells.count > 0)
my guess if statement above running when selectedcells.count = -1
lastly, suggestion, instead of
where productid= " + cell.value + " "
i use
where productid='" + cell.value + "'"
the ' important mitigating possible errors.
Comments
Post a Comment