1

我的 C# windows 应用程序中有一个 gridview ......它允许被编辑,我想要一个特殊的单元格(名为“Price”)来只允许按键上的数字......我使用下面的代码用于 texboxes 只允许数字。 .. 在哪个网格视图事件中我应该编写这段代码?

     private void txtJustNumber_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsDigit((char)(e.KeyChar)) &&
            e.KeyChar != ((char)(Keys.Enter)) &&
            (e.KeyChar != (char)(Keys.Delete) || e.KeyChar == Char.Parse(".")) &&
            e.KeyChar != (char)(Keys.Back))
        {
            e.Handled = true;
        }
    }
4

3 回答 3

2
You can use CellValidating event of DataGridView.


private void dataGridView1_CellValidating(object sender,
        DataGridViewCellValidatingEventArgs e)
    {
        // Validate the Price entry.
        if (dataGridView1.Columns[e.ColumnIndex].Name == "Price")
        {
        }
    }
于 2012-10-31T07:16:22.250 回答
2

thx伙计们......我使用了下面的代码,我的问题解决了......

    public Form1()
    {
        InitializeComponent();
        MyDataGridViewInitializationMethod();
    }

    private void MyDataGridViewInitializationMethod()
    {
        gvFactorItems.EditingControlShowing +=
            new DataGridViewEditingControlShowingEventHandler(gvFactorItems_EditingControlShowing);
    }

    private void gvFactorItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        e.Control.KeyPress += new KeyPressEventHandler(Control_KeyPress); ;
    }

    private void Control_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (!char.IsDigit((char)(e.KeyChar)) &&
            e.KeyChar != ((char)(Keys.Enter)) &&
            (e.KeyChar != (char)(Keys.Delete) || e.KeyChar == Char.Parse(".")) &&
            e.KeyChar != (char)(Keys.Back))
        {
            e.Handled = true;
        }
    }
于 2012-11-01T17:33:03.487 回答
0

我认为你应该看看这个,它会有所帮助:-

DataGridView keydown 事件在 C# 中不起作用

于 2012-10-31T13:06:32.027 回答