Click here to Skip to main content
16,018,057 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Everyone,

I facing a problem in writing KeyCode inside KeyCode, which is I want to execute my code using KeyCode but the input is different. The first "if" is working but for the second "if else" is not give me any output. Here I attached my code.

What I have tried:

private void MainWindow_KeyDown(object sender, KeyEventArgs e)
       {
           if (e.KeyCode == Keys.NumPad0)
           {
               funcDisp.Text = "Pwr.Wheel";
               funcDisp.ForeColor = Color.LimeGreen;
               set1Disp.Text = "Up";
               set1Disp.ForeColor = Color.LimeGreen;
               set2Disp.Text = "Down";
               set2Disp.ForeColor = Color.LimeGreen;

               if (e.KeyCode == Keys.NumPad1)
               {
                   textVolt.Text = "UP";
               }

               else if (e.KeyCode == Keys.NumPad3)
               {
                   textBrake.Text = "DOWN";
               }

           }
Posted
Updated 6-May-22 18:22pm
Comments
[no name] 6-May-22 19:44pm    
Your "if's" (2 and 3) are inside the first (if); that won't work. Also, use a switch instead.
Member 15627303 6-May-22 20:37pm    
you mean like this:

private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.NumPad0)
{
funcDisp.Text = "Pwr.Wheel";
funcDisp.ForeColor = Color.LimeGreen;
set1Disp.Text = "Up";
set1Disp.ForeColor = Color.LimeGreen;
set2Disp.Text = "Down";
set2Disp.ForeColor = Color.LimeGreen;

switch (e.KeyCode)
{
case Keys.NumPad1:
{
textVolt.Text = "UP";
break;
}

case Keys.NumPad2:
{
textBrake.Text = "DOWN";
break;
}
}
}

1 solution

Look at your code: what you have is this:
C#
if (x == 0)
   foo();
   if (x == 1)
      bar();
   else if (x == 2)
      foobar();
Or later this:
C#
if (x == 0)
   foo();
   switch (x)
      case 1:
         bar();
         break;
      case 2:
         foobar();
         break;
If x is equal to zero, it cannot at the same time be equal to one or two. You need to restructure your code so that the values can be checked properly - changing test constructs won't do that when its; teh whole structure that is wrong.
C#
if (x == 0)
   foo();
if (x == 1)
   bar();
else if (x == 2)
   foobar();
Or this:
C#
if (x == 0)
   foo();
else if (x == 1)
   bar();
else if (x == 2)
   foobar();
Or perhaps this:

C#
switch (x)
   case 0:
      foo();
      break;
   case 1:
      bar();
      break;
   case 2:
      foobar();
      break;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900