Reputation: 297
I have a PreviewKeyDown
event in my grid and i want to let just numeric value and (0,2) decimal value.
private void dgvUser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
colUser = dgvUser.CurrentCell.ColumnIndex;
rowUser = dgvUser.CurrentCell.RowIndex;
DataGridViewCell tc = dgvUser[colUser, rowUser];
valueUser = Convert.ToDouble(tc.Value);//code breaks here
if (e.KeyData == Keys.Enter && dgvUser.CurrentCell.ColumnIndex == 2 && handledUser == true)
{
DragerClass.Dedektör.Dedektor_A1Set[Convert.ToInt32(dgvUser.Rows[rowUser].Cells[0].Value) - 1] = valueUser;
BindUserGrid(userPagingUpdate[0], userPagingUpdate[1]);
logValues(Convert.ToInt32(dgvUser.Rows[rowUser].Cells[0].Value) - 1);
handledUser = false;
}
}
When i enter non numeric value code breaks in valueUser = Convert.ToDouble(tc.Value);
line. how can i prevent that?
Upvotes: 0
Views: 657
Reputation: 122
Another solution would be to set the DataGridViewCell.ValueType
that you use as a template for your column to typeof(decimal)
this will create a DataError Event
every time the user tries to input a value different to what you have specified. You can then handle that DataError Event
to whatever you like.
Upvotes: 0
Reputation: 2605
Either you can use a Try/Catch statement,
try
{
valueUser = Convert.ToDouble(tc.Value);
}
catch
{
// if the above line throws an exception deal with it here.
}
or you could use double.TryParse()
double valueUser;
bool isNumber = double.TryParse(tc.Value,out valueUser);
Upvotes: 0
Reputation: 11
You can use Double.TryParse
method:
if (Double.TryParse(tc.Value.ToString(), out valueUser))
{
//success
}
else
{
//fail
}
Upvotes: 1