0

I have a gridview in my C# windows application ... It allowed to be edited and I want a special cell (named "Price") to just allow number on keypress ... I use the code below for texboxes to just allow numbers ... in which event of grid view should I write this code?

     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;
        }
    }
mjyazdani
  • 2,110
  • 6
  • 33
  • 64
  • Why don't you just check for which cell is being edited on key press and then handle the key press event accordingly? – Derek Oct 31 '12 at 09:13
  • @Derek I have some other textboxes on the form ... how can i handle all of them! can u explain more please? – mjyazdani Oct 31 '12 at 09:24

3 Answers3

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")
        {
        }
    }
1

thx guys ... I used below code and my problem resolved ...

    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;
        }
    }
mjyazdani
  • 2,110
  • 6
  • 33
  • 64
0

I think you should take a look at this, it will help :-

DataGridView keydown event not working in C#

Community
  • 1
  • 1
Derek
  • 8,300
  • 12
  • 56
  • 88