I am new with c#. I would like to read only odd number from trackbar. And if input is even then show an error message. Here is my try. It works even input is an even number,no error message comes. Thanks in advance.
private void button1_Click_1(object sender, EventArgs e)
{
if (sliderKernel.Value % 2 == 0)
{
try {
int a=5;
}
catch {
MessageBox.Show("Enter an odd number");
}
}
}
If you must use try-catch block, you will need to throw an exception from try block with an appropriate message whenever an even number is encountered and handle the exception in a catch block accordingly as:
private void button1_Click_1(object sender, EventArgs e)
{
try
{
if (sliderKernel.Value % 2 == 0)
throw new Exception("Enter an odd number");
// handle odd numbers here
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This can also be achieved without try-catch as:
private void button1_Click_1(object sender, EventArgs e)
{
if (sliderKernel.Value % 2 == 0)
{
MessageBox.Show("Enter an odd number");
return;
}
// handle odd numbers here
}