Home > Blockchain >  Why is DataGridView.CellValueChanged repeatedly triggered when user hits <Enter>?
Why is DataGridView.CellValueChanged repeatedly triggered when user hits <Enter>?

Time:10-12

I'm using a DataGridView to display data, with one of the columns being editable - the user can double-click and edit the text; when the user hits <Enter> the CellValueChanged event is triggered.

private void dgvCompanyNameAliases_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    var row = dgvCompanyNameAliases.Rows[e.RowIndex];
    var companyNameMapping = (CompanyNameMapping)(row.Tag ?? row.DataBoundItem);
    companyNameMapping.Alias = dgvCompanyNameAliases.CurrentCell.EditedFormattedValue.ToString();

    if (String.IsNullOrWhiteSpace(companyNameMapping.Alias))
    {
        if (MessageBox.Show(String.Format(Resources.FrmSettings.ErrorQuestion_DeleteCompanyAliasConfirmMessage, companyNameMapping.Name),
                            Resources.FrmSettings.ErrorQuestion_DeleteCompanyAliasConfirmTitle,
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Question)
            == DialogResult.No)
        {
            return;
        }

        _configSettings.Policies.ProjectNamingPolicies.CompanyNameMappings.DeleteAlias(companyNameMapping, _configSettings.Username);
    }
    else
    {
        companyNameMapping.Recorded = new Recorded
                                      {
                                          By = _configSettings.Username,
                                          On = DateTime.Now
                                      };

        _configSettings.Policies.ProjectNamingPolicies.CompanyNameMappings.UpdateAlias(companyNameMapping);
    }

    LoadCompanyNameAliases();
}

private void LoadCompanyNameAliases()
{   
    dgvCompanyNameAliases.DataSource = _configSettings.Policies.ProjectNamingPolicies.CompanyNameMappings.GetAllAliases()
                                                      .OrderBy(companyNameMapping => companyNameMapping.Name)
                                                      .ToList();
}

However, although this works, the event handler is being repeatedly triggered until the user selects No on the question dialog.

What am I doing wrong?

CodePudding user response:

Try this. Put it on the first line of the method. Your codes just work if isInEditMode true.

if (e.ColumnIndex < 0 || e.RowIndex < 0 || !grid[e.ColumnIndex, e.RowIndex].IsInEditMode) return;

CodePudding user response:

I solved this problem by moving all the logic from the CellValueChanged event handler to CellEndEdit.

  • Related