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

Bah*_*man 5 .net c# vb.net datagridview winforms

有没有一种方法可以只将某些字符添加到datagridview单元中?像“ 1234567890”?

Dav*_*all 4

据我所知,您可以使用两种方法来实现此目的。第一个(我认为最好的)是使用 CellValidating 事件DataGridView并检查输入的文本是否为数字。

下面是一个设置行错误值的示例(带有附加的 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;
    }
Run Code Online (Sandbox Code Playgroud)

第二种方法是使用 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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