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

|| 有没有一种方法可以只将某些字符添加到datagridview单元中? 喜欢\'1234567890 \'?     
已邀请:
我知道有两种方法可以用于此目的。第一个(也是我认为最好的方法)是使用
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;
    }
}
与此有关的一个重要注意事项是要小心,删除编辑控件show方法中控件上的事件处理程序。这很重要,因为“ 0”会为相同类型的每个单元格重复使用同一对象,包括跨不同的列。如果将事件处理程序附加到一个文本框列中的控件,则网格中的所有其他文本框单元格将具有相同的处理程序!同样,将附加多个处理程序,每次显示控件时都将一个。 第一个解决方案来自此MSDN文章。第二个来自这个博客。     

bab

如果您希望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()方法,请参见此SO问题,以了解一些从字符串中删除特殊字符的出色方法。     

要回复问题请先登录注册