Link to home
Start Free TrialLog in
Avatar of MSFanboy
MSFanboyFlag for Germany

asked on

Allow only positive integer values in a certain Column of DataGridView?

Hello,

does someone have me please a little  code snippet, how I can limit the user input in the DataGridView_CellValidating Event to only positive integer values?
Avatar of abel
abel
Flag of Netherlands image

Something like this?

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    int value = 0;
    int.TryParse(e.FormattedValue.ToString(), out value);
    if (value > 0)
        e.Cancel = false;
    else
        e.Cancel = true;
}

Open in new window

If you mean strictly positive, the code above works. If you mean to include zero, the code ">" needs to be replaced with ">=".

You can use a shortcut for the if/else. I wrote it out to show what is going on, but if you are familiar with booleans and if you like short code, you can do this as well:

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    int value = 0;
    int.TryParse(e.FormattedValue.ToString(), out value);
    e.Cancel = value <= 0;
}

Open in new window

Avatar of Kevin Robinson
Kevin Robinson

Try http://www.componentfactory.com/ FREE toolkit.  It has a tool for this.

ASKER CERTIFIED SOLUTION
Avatar of MSFanboy
MSFanboy
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Glad you found a solution, but why then did you ask "how I can limit the user input in the DataGridView_CellValidating event..."? If you want to diverge from your original q. please inform the involved experts in the thread.