c# – Undo EditingControlShowing

Question:

I have a DataGrid in which a given column can only be inserted numbers, so I used "EditingControlShowing" to evaluate user input in that column and only allow numbers.

string columnName = dataGridView_CP.CurrentCell.OwningColumn.Name;
IEnumerable<string> itemsNumero = new List<string> { "C_Altura" };
IEnumerable<string> itemsString = new List<string> { "Column_Id", "Column_Lote", "Column_Data" };

DataGridViewTextBoxEditingControl tb = (DataGridViewTextBoxEditingControl)e.Contro;

if (itemsNumero.Contains(columnName))
{
     tb.KeyPress -= new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
     tb.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
     tb.TextChanged -= new EventHandler(dataGridViewTextBox_TextChanged);
     tb.TextChanged += new EventHandler(dataGridViewTextBox_TextChanged);
}

if (itemsString.Contains(columnName))
{
     tb.KeyPress -= new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
     tb.TextChanged -= new EventHandler(dataGridViewTextBox_TextChanged);
}

It turns out that if the user enters to type something in that column the property works, but when he clicks on another cell to type data, the verification of typing only numbers remains active. Is there a way to disable this entry before entering another cell?

The problem seems to be in the "TextChanged" which executes before the next cell enters its "EditingControlShowing".

Answer:

The problem occurs is because you set the event to all columns, and you must define the event only on the columns you want to consist of, you can do this by getting the index of the column you want to consist of, see this code I already use in some of my applications:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    // Aqui pega o index da coluna que está selecionada.
    int colIndex = this.dataGridView1.CurrentCell.ColumnIndex;

    // Aqui eu verifico se a coluna que está selecionada é a coluna que vou consistir a entrada de dados.
    if (colIndex == 0)
        e.Control.KeyPress += dataGridView1_KeyPress;
    else
        e.Control.KeyPress -= dataGridView1_KeyPress;
}

private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
    // Aqui eu só permito a informação de números
    e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == 8);
}
Scroll to Top
AllEscort