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

时间:2011-04-16 15:52:54

标签: c# .net vb.net winforms datagridview

有没有办法只将某些字符添加到datagridview单元格? 比如'1234567890'?

2 个答案:

答案 0 :(得分:4)

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

以下是设置行错误值的示例(使用额外的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;
    }

第二种方法是使用EditingControlShowing事件并将事件附加到单元格的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为相同类型的每个单元重用相同的对象,包括跨不同的列。如果将事件处理程序附加到一个文本框列中的控件,则网格中的所有其他文本框单元格将具有相同的处理程序!此外,还将附加多个处理程序,每次显示一个控件。

第一个解决方案来自this MSDN article。第二个来自this blog

答案 1 :(得分:0)

如果您希望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()方法,请参阅this SO question以了解从字符串中删除特殊字符的一些优秀方法。