Click here to Skip to main content
15,917,328 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
if (e.Control && e.KeyCode == Keys.D2)
          {

              textBox1.Text="2";
          }
           {


I want
if (e.Control && e.KeyCode == Keys.D2)
only to happen if textbox1.Text = "test".

How can I do this
This is very new to me, sorry

What I have tried:

Posted
Updated 13-Mar-20 6:57am
v2

You can just add a third condition:
C#
if (textBox1.Text.Equals("test") && e.Control && e.KeyCode == Keys.D2)
{
   // ...
}

Or you can nest if blocks:
C#
if (textBox1.Text.Equals("test"))
{
   if (e.Control && e.KeyCode == Keys.D2)
   {
      // ...
   }
}
 
Share this answer
 
C#
if (textBox1.Text == "test")
   {
   if (e.Control && e.KeyCode == Keys.D2)
      {
      textBox1.Text="2";
      }
   }
Or
C#
if (textBox1.Text == "test" && e.Control && e.KeyCode == Keys.D2)
   {
   textBox1.Text="2";
   }
 
Share this answer
 
v2
Comments
F-ES Sitecore 13-Mar-20 12:50pm    
textBox1.Text = "test"

First day learning c#? ;)
OriginalGriff 13-Mar-20 13:07pm    
Herself is doing an online Dysphagia course. Which means every time I sit down I get a scream for help on where to click on a site I've never used, or to answer a multiple choice question on a subject I know sod-all about. It's wearing me down a little ...
As previously stated; you could either compound the IF statements into one or nest them
C#
// compounded
if (e.Control) && e.KeyCode == Keys.D2 && textbox1.Text == "test" ) {
	textBox1.Text="2";
}
// nested
if (e.Control) && e.KeyCode == Keys.D2) {
	if (textbox1.Text == "test" ) {
		textBox1.Text="2";
	}
}
Now one thing about the nested version is this could be further expanded if you had to add in various renditions of the third condition
C#
if (e.Control) && e.KeyCode == Keys.D2) {
	if (textbox1.Text == "test" ) { textBox1.Text="2"; }
	if (textbox1.Text == "exam" ) { textBox1.Text="3"; }
}
Or if there would be a bunch of textbox1.Text values to check, you could utilize a switch...case block
C#
if (e.Control) && e.KeyCode == Keys.D2) {
	switch(textbox1.Text) {
		case "test":
			textBox1.Text="2";
			break;
		case "exam":
			textBox1.Text="3";
			break;
		case "quiz":
		case "check":
			textBox1.Text = "4";
			break;
		default:
			textBox1.text = "0"
			break;
	}	
}
Reference:
C# switch statement | Microsoft Docs[^]
Please note that all of these comparisons are case-sensitive by default
 
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