【问题标题】:allow just number in a gridviewcell on editing在编辑时只允许在 gridviewcell 中输入数字
【发布时间】:2012-10-31 07:01:40
【问题描述】:

我的 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;
        }
    }

【问题讨论】:

  • 为什么不检查按键时正在编辑哪个单元格,然后相应地处理按键事件?
  • @Derek 我在表单上还有其他一些文本框……我该如何处理所有这些文本框!你能解释一下吗?

标签: c# gridview


【解决方案1】:
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")
        {
        }
    }

【讨论】:

  • 那么...我应该如何验证按下的键? "e" 与 KeyPress 事件中的 "e" 不同...
  • 我按照你的要求告诉了你事件。
【解决方案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;
        }
    }

【讨论】:

    【解决方案3】:

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

    DataGridView keydown event not working in C#

    【讨论】:

      猜你喜欢
      • 2014-09-14
      • 2013-08-05
      • 2018-03-06
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 2017-11-13
      相关资源
      最近更新 更多