只允许在datagridview单元格中键入一些字符



是否有办法让只有某些字符被添加到datagridview单元格?像"1234567890"?

我知道有两种方法可以用于此。第一个(我认为最好的)是在DataGridView上使用cellvalidation事件,并检查输入的文本是否为数字。

下面是一个设置行错误值的例子(如果用户取消编辑,则使用额外的CellEndEdit事件处理程序)。

private void dataGridView1_CellValidating(object sender,
        DataGridViewCellValidatingEventArgs e)
    {
        string headerText = 
            dataGridView1.Columns[e.ColumnIndex].HeaderText;
        // Abort validation if cell is not in the Age column.
        if (!headerText.Equals("Age")) return;
        int output;
        // Confirm that the cell is an integer.
        if (!int.TryParse(e.FormattedValue.ToString(), out output))
        {
            dataGridView1.Rows[e.RowIndex].ErrorText =
                "Age must be numeric";
            e.Cancel = true;
        }
    }
    void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        // Clear the row error in case the user presses ESC.   
        dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty;
    }

第二种方法是使用editingcontrolshow事件并将事件附加到单元格的KeyPress -我不是这种方法的粉丝,因为它静默地阻止了非数字键的输入-尽管我认为您可以给出一些反馈(如铃声响起)它只是感觉像更多的工作相比,其他方式。

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    e.Control.KeyPress -= TextboxNumeric_KeyPress;
    if ((int)(((System.Windows.Forms.DataGridView)(sender)).CurrentCell.ColumnIndex) == 1)
    {
         e.Control.KeyPress += TextboxNumeric_KeyPress;
    }
}
private void TextboxNumeric_KeyPress(object sender, KeyPressEventArgs e)
{
    bool nonNumberEntered = true;
    if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8)
    {
        nonNumberEntered = false;
    }
    if (nonNumberEntered)
     {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
    }
    else
    {
        e.Handled = false;
    }
}

一个重要的注意事项是,在编辑控件显示方法中删除控件上的事件处理程序时要小心。这很重要,因为DataGridView为相同类型的每个单元格重用相同的对象,包括跨不同列。如果将事件处理程序附加到一个文本框列中的控件,则网格中的所有其他文本框单元格将具有相同的处理程序!此外,还将附加多个处理程序,每次显示控件一个处理程序。

第一个解决方案来自这篇MSDN文章。第二个来自这个博客

如果您希望datagridview简单地为用户删除无效字符,而不是发出错误消息,请使用datagridview . cellparsing()。此事件仅在编辑单元格后触发,并允许您覆盖已输入的内容。

例如:

private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
    // If this is column 1
    if (e.ColumnIndex == 1)
    {
        // Remove special chars from cell value
        e.Value = RemoveSpecialCharacters(e.Value.ToString());
        e.ParsingApplied = true;
    }
}

对于RemoveSpecialCharacters()方法,请参阅这个问题,了解从字符串中删除特殊字符的一些优秀方法。

最新更新