Do not let insert same value in a Datagridview C#

Asked

Viewed 99 times

1

I own a DataGridView where I have a column called Ramal, where the specific seller’s extension will go.

How to do that when I type in a line an existing extension, appear a message that cannot be inserted? As an example below:

inserir a descrição da imagem aqui

2 answers

1


Go to your event DataGridView and choose the option CellEndEdit.

Within this event method enter the following code:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    string v = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value?.ToString().Trim();
    foreach (DataGridViewRow row in this.dataGridView1.Rows)
    {
        if (row.Index >= this.dataGridView1.Rows.Count - 1) break;
        if (row.Cells[3].Value?.ToString().Trim() == v && row.Index != e.RowIndex)
        {
            MessageBox.Show("Opa, já existe um ramal igual a esse");
            this.dataGridView1[e.ColumnIndex, e.RowIndex].Value = null;
            break;
        }
    }
}

Cells[3] is the column where the branches are located.

When someone type an extension that already exists in the column, the message will appear.

-2

The ideal events for such validation are Columnchanged and Rowchanged. Columnchanged occurs soon after the user has changed the value of a column is ideal for column-by-column validation. Rowchanged occurs after that the user has completed the change in line.

  • ok. But what would be an interesting method to be able to do this check? I can’t find anywhere ;'(

  • 1

    It would be more useful if you include yourself an example in your reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.