Rusty Shackleford Rusty Shackleford - 1 year ago 107
C# Question

DataGridView Deleting/Updating problems

So, I've been doing some practice code for a few days. I'm working on using a DataGridView, without a database. Everything seems to work, save for one problem. Whenever I click the delete or update button without selecting a record, the form crashes. Here's the update function:

private void btnUpdate_Click(object sender, EventArgs e)
if (dgvProfiles.SelectedCells == null)
MessageBox.Show("No record was selected to update.");

else {
for (int row = 0; row < dgvProfiles.Rows.Count; row++)
for (int col = 0; col < dgvProfiles.Columns.Count; col++)
if (dgvProfiles.Rows[row].Cells[col].Value != null &&
MessageBox.Show("Duplicate email was entered.");
DataGridViewRow newDataRow = dgvProfiles.Rows[indexRow];
newDataRow.Cells[0].Value = txtFirstName.Text;
newDataRow.Cells[1].Value = txtLastName.Text;
newDataRow.Cells[2].Value = txtPhone.Text;
newDataRow.Cells[3].Value = txtEmail.Text;
newDataRow.Cells[4].Value = txtCity.Text;
newDataRow.Cells[5].Value = cbxState.Text;
newDataRow.Cells[6].Value = txtZip.Text;

Thanks in advance!

Answer Source

SelectedCells is a collection the system provides.

It is never null.

It can be emtpy though, so if (for some reason) you want to check you can write :

if (dgvProfiles.SelectedCells.Count <= 0)..


if (dgvProfiles.SelectedRows.Count <= 0)..

I'm not sure why you demand a row or cell to be selected in the first place, though. Shouldn't saving always work..?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download