Ashish
Ashish

Reputation:

How can I restrict a user to entering only numeric values in a specific cell in a DataGridView column?

I have a DataGridView control in which I want to restrict the user to entering only numeric values for a cell under a particular column. How can I accomplish this type of validation in DataGridView cells?

It is possible when I create a simple text box, but how can I validate a DataGridView Cell?

Upvotes: 2

Views: 4429

Answers (3)

Muhammad Mobeen Qureshi
Muhammad Mobeen Qureshi

Reputation: 1182

  • Add an event of EditingControlShowing
  • In EditingControlShowing, check that if the current cell lies in the desired column.
  • Register a new event of KeyPress in EditingControlShowing(if above condition is true).
  • Remove any KeyPress event added previously in EditingControlShowing.
  • In KeyPress event, check that if key is not digit then cancel the input.

Example:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
            if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
            {
                TextBox tb = e.Control as TextBox;
                if (tb != null)
                {
                    tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
                }
            }
        }

private void Column1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

Upvotes: 1

pei
pei

Reputation:

Use cellValidating event:

Grid.CellValidating += new DataGridViewCellValidatingEventHandler(Grid_CellValidating);

Grid_CellValidating(object sender, args)
{
XXXX
}

Upvotes: 1

ChrisF
ChrisF

Reputation: 137148

You can set the type of data the column will hold as the following code snippet illustrates:

var columnSpec = new DataColumn();
columnSpec.DataType = <your type>
// Other initialisation
dataTable.Columns.Add(columnSpec);

dataGridView.DataSource = dataTable;

If you are working directly on the DataGridView then the DataGridViewColumn class has the following property:

ValueType - Gets or sets the data type of the values in the column's cells.

If you create your columns using this class rather than the more specialised classes DataGridViewCheckBoxColumn etc. this might do want you want.

Upvotes: 1

Related Questions