Hi Dears
I want check the value of my gridColumns , I want user only type digit, I don't want let user to type any thing else except digit
How I can check it? and in which event I have to write this codes?

Recommended Answers

All 18 Replies

You can try this snippet

thanks
but it is for textbox and i know it myself i want use it for cells in my grid how I can use it for grid(mean in which event of my grid i can use it)
before i try in KeyPress but it dosen't work you know it never go to KeyPress Event when the user is typing

Yes I know it's code for a TextBox. But it should be easily adapted to a DataGridView, because when you are editing a cell in the grid you are working with a textbox.

yes you are right how i can get to this textbox and i write my codes in which event?

Danny is right but it creates a repository textbox on the fly and I can't find the event to hook in for this. You could also handle the cell validation event:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace daniweb
{
  public partial class frmGridView2 : Form
  {
    DataTable dt;
    public frmGridView2()
    {
      InitializeComponent();
    }

    private void frmGridView2_Load(object sender, EventArgs e)
    {
      dt = new DataTable();
      dt.Columns.Add(new DataColumn("string1", typeof(string)));
      dt.Columns.Add(new DataColumn("int1", typeof(int)));

      DataRow row = dt.NewRow();
      row[0] = "string value";
      row[1] = 31415; //does this # look familiar? +rep for who gets it! should be a no-brainer
      dt.Rows.Add(row);

      dataGridView1.Columns[0].DataPropertyName = "string1";
      dataGridView1.Columns[0].Name = "string1";
      dataGridView1.Columns[1].DataPropertyName = "int1";
      dataGridView1.Columns[1].Name = "int1";
      dataGridView1.DataSource = dt;
    }

    private void button1_Click(object sender, EventArgs e)
    {
      System.Diagnostics.Debugger.Break();
    }

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
      if (e.ColumnIndex == dataGridView1.Columns["int1"].Index) //this is our numeric column
      {
        int i;
        if (!int.TryParse(Convert.ToString(e.FormattedValue), out i))
        {
          e.Cancel = true;
          MessageBox.Show("must be numeric");
        }
      }
    }
  }
}

thanks dear
but when the user type wrong(charcter) my form lock and when the user correct it also when want to exit messagebox show how let user when correct it and type digit exit?

I don't understand what you're saying.... please clarify

I mean when the I type Char this message shows and then I correct it but although it was correct when I want to close this form this message shows also and don't let to close the form

Now I want when Correct it the cursor goes to the new row how it happen?

So do you have it working or not?

hi
I have the same problem.and your solution worked.so thx.
but I want not to allow user to write even a letter.sth that we write in KeyPress Event.
what should I do?

Dajer: Create your own thread to ask the question. You should not start asking questions on other peoples thread. We want to keep DaniWeb clean! :)

I asked my question here because my question was the same.
with a bit different.it's clear from my question.

Yes it works Thanks so
Dajer is right I want also user couldn't write when want to write char How do it?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace daniweb
{
  public partial class frmGridView2 : Form
  {
    DataTable dt;
    private TextBox editingBox; //I cant find where the gridView holds the reference
    public frmGridView2()
    {
      InitializeComponent();
      editingBox = default(TextBox);
    }

    private void frmGridView2_Load(object sender, EventArgs e)
    {
      dt = new DataTable();
      dt.Columns.Add(new DataColumn("string1", typeof(string)));
      dt.Columns.Add(new DataColumn("int1", typeof(int)));

      DataRow row = dt.NewRow();
      row[0] = "string value";
      row[1] = 31415;
      dt.Rows.Add(row);

      dataGridView1.Columns[0].DataPropertyName = "string1";
      dataGridView1.Columns[0].Name = "string1";
      dataGridView1.Columns[1].DataPropertyName = "int1";
      dataGridView1.Columns[1].Name = "int1";
      dataGridView1.DataSource = dt;
    }

    private void button1_Click(object sender, EventArgs e)
    {
      System.Diagnostics.Debugger.Break();
    }

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
      
      if (e.ColumnIndex == dataGridView1.Columns["int1"].Index) //this is our numeric column
      {
        int i;
        if (!int.TryParse(Convert.ToString(e.FormattedValue), out i))
        {
          e.Cancel = true;
          MessageBox.Show("must be numeric");
        }
      }
    }

    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
      if (dataGridView1.CurrentCell.ColumnIndex < 0) //i dont know if it ever fires with -1, so to be safe
        return;
      if (dataGridView1.CurrentCell.ColumnIndex != dataGridView1.Columns["int1"].Index) //not our numeric column
        return;

      TextBox tb = (dataGridView1.EditingControl as TextBox);
      if (tb == null)
      {
        System.Diagnostics.Debugger.Break(); //you changed it to a non TextBox control. Add more support
        return;
      }
      editingBox = tb;
      tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
      tb.TextChanged += new EventHandler(tb_TextChanged);
    }

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
      if (editingBox != null)
      {
        //Need to clean up our event handlers so the other columns can have string values
        editingBox.KeyPress -= new KeyPressEventHandler(tb_KeyPress);
        editingBox.TextChanged -= new EventHandler(tb_TextChanged);
      }
    }

    void tb_KeyPress(object sender, KeyPressEventArgs e)
    {
    void tb_KeyPress(object sender, KeyPressEventArgs e)
    {
      if (!char.IsNumber(e.KeyChar))
        e.Handled = true;
    }
    void tb_TextChanged(object sender, EventArgs e)
    {
      //This handles if they paste crap in the textbox since that doesn't fire the KeyDown event
      TextBox tb = (sender as TextBox);
      int i;
      if (!string.IsNullOrEmpty(tb.Text) && !int.TryParse(tb.Text, out i))
      {
        StringBuilder sb = new StringBuilder();
        for (int i1 = 0; i1 < tb.Text.Length; i1++)
        {
          if (char.IsNumber(tb.Text[i1]))
            sb.Append(tb.Text[i1]);
        }
        tb.Text = sb.ToString();
      }
    }
  }
}

There was some mistakes in the last post:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace daniweb
{
  public partial class frmGridView2 : Form
  {
    DataTable dt;
    private TextBox editingBox; //I cant find where the gridView holds the reference
    public frmGridView2()
    {
      InitializeComponent();
      editingBox = default(TextBox);
    }

    private void frmGridView2_Load(object sender, EventArgs e)
    {
      dt = new DataTable();
      dt.Columns.Add(new DataColumn("string1", typeof(string)));
      dt.Columns.Add(new DataColumn("int1", typeof(int)));

      DataRow row = dt.NewRow();
      row[0] = "string value";
      row[1] = 31415;
      dt.Rows.Add(row);

      dataGridView1.Columns[0].DataPropertyName = "string1";
      dataGridView1.Columns[0].Name = "string1";
      dataGridView1.Columns[1].DataPropertyName = "int1";
      dataGridView1.Columns[1].Name = "int1";
      dataGridView1.DataSource = dt;
    }

    private void button1_Click(object sender, EventArgs e)
    {
      System.Diagnostics.Debugger.Break();
    }

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
      
      if (e.ColumnIndex == dataGridView1.Columns["int1"].Index) //this is our numeric column
      {
        int i;
        if (!int.TryParse(Convert.ToString(e.FormattedValue), out i))
        {
          e.Cancel = true;
          MessageBox.Show("must be numeric");
        }
      }
    }

    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
      if (dataGridView1.CurrentCell.ColumnIndex < 0) //i dont know if it ever fires with -1, so to be safe
        return;
      if (dataGridView1.CurrentCell.ColumnIndex != dataGridView1.Columns["int1"].Index) //not our numeric column
        return;

      TextBox tb = (dataGridView1.EditingControl as TextBox);
      if (tb == null)
      {
        System.Diagnostics.Debugger.Break(); //you changed it to a non TextBox control. Add more support
        return;
      }
      editingBox = tb;
      tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
      tb.TextChanged += new EventHandler(tb_TextChanged);
    }

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
      if (editingBox != null)
      {
        //Need to clean up our event handlers so the other columns can have string values
        editingBox.KeyPress -= new KeyPressEventHandler(tb_KeyPress);
        editingBox.TextChanged -= new EventHandler(tb_TextChanged);
        editingBox = null;
      }
    }

    void tb_KeyPress(object sender, KeyPressEventArgs e)
    {
      if (!char.IsNumber(e.KeyChar))
        e.Handled = true;
    }
    void tb_TextChanged(object sender, EventArgs e)
    {
      //This handles if they paste crap in the textbox since that doesn't fire the KeyDown event
      TextBox tb = (sender as TextBox);
      int i;
      if (!string.IsNullOrEmpty(tb.Text) && !int.TryParse(tb.Text, out i))
      {
        StringBuilder sb = new StringBuilder();
        for (int i1 = 0; i1 < tb.Text.Length; i1++)
        {
          if (char.IsNumber(tb.Text[i1]))
            sb.Append(tb.Text[i1]);
        }
        tb.Text = sb.ToString();
      }
    }
  }
}

Thanks Friends

Please mark this thread as solved if you have found an answer to your question and good luck!

I spent a lot of time on this thread :P

commented: thx alot. +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.