tags:

views:

1657

answers:

2

Hi ,

I am new to DataGridView control so please exuse me if I ask any obvious question.

I have a datagridview control , in which I want to restrict user to enter only numeric values only for a cell under a particular column. What will be the best way to create such type of validation in DataGridView cells.

It is possible when we create a simple text box , but how can we validate a DataGridView Cell. It will be nice if anybody provide a small code snippet to achieve this.

Thanks in advance, Ashish

+1  A: 

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.

ChrisF
Thanks for the reply. But I don't find DatType property in DataGridViewTextBoxColumn column in DataGridView control
Can you post the code you're using to define your DataGridView? My answer assumed that the data was in a DataTable and the DataGridView is just for display
ChrisF
There wont be a DataType property in DataGridViewTextBoxColumn as it already has type - Text.
ChrisF
A: 

use cellValidating event

Grid.CellValidating += new DataGridViewCellValidatingEventHandler(Grid_CellValidating);

Grid_CellValidating(object sender, args) { XXXX }