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.");
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.Value = txtFirstName.Text;
newDataRow.Cells.Value = txtLastName.Text;
newDataRow.Cells.Value = txtPhone.Text;
newDataRow.Cells.Value = txtEmail.Text;
newDataRow.Cells.Value = txtCity.Text;
newDataRow.Cells.Value = cbxState.Text;
newDataRow.Cells.Value = txtZip.Text;
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..?