Rusty Shackleford
Rusty Shackleford

Reputation: 49

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 &&
                      dgvProfiles.Rows[row].Cells[col].Value.Equals(txtEmail.Text.Trim()))
                    {
                        MessageBox.Show("Duplicate email was entered.");
                        return;
                    }
                }
            }
            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!

Upvotes: 0

Views: 40

Answers (1)

TaW
TaW

Reputation: 54433

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)..

or

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..?

Upvotes: 1

Related Questions