Windows Forms C# - Variables, Strings and Boolean

2018/02/02 02:07
Variables:
The variable is a container of information that can change its value. It provides the opportunity for:
  • Keeping information; 
  • Extracting the saved information; 
  • Modification of the saved information. 
Programming in C Sharp is related to the constant use of variables in which data is stored and processed.
Characteristics of the variables - the variables are characterized by:
  • Name (identifier), e.g. age; 
  • Type (the information stored therein), eg int; 
  • Value (saved information), for example 25. 

A variable is a named memory area in which a value of a given type is available in the program under its name. Variables can be stored directly in the program memory (in the stack) or in the dynamic memory that stores larger objects (for example, character strings and arrays).
Naming a variable:
When we want the compiler to assign an area to the memory for some information used in our program, we need to assign a name to it. It serves as an identifier and allows us to refer to the required area of memory.
The name of the variables can be any of our choice, but we have to follow certain rules:
  • Variable names are formed by the letters a-z, A-Z, digits 0-9, and the '_' symbol. 
  • Variable names cannot start with a digit. 
  • Variable names cannot match a C# reserved keyword. 
The following table lists all keywords in C #.






abstractdelegateifoverridevoid
asdoimplicitparamsstructwhile
basedoubleinprivateswitch
boolelseintprotectthis
breakenuminterfacepublicthrow
byteeventinternalreadonlytrue
caseexplicitisreftrytypeof
catchexternlockreturnunit
charfalselongsbyteulong
checkedfinallynamespacesealedunchecked
classfixednewshortunsafe
constfloatnullsizeofushort
continueforobjectstachallocusing
decimalforeachoperatorstaticvirtual
defaultgotooutstringvolatile

Strings:
Strings are a series of symbols. They are declared with the keyword string in C#. Their default value is null. Strings are enclosed in double quotes. Various word-processing operations can be performed on them: concatenation, separating by a separator, searching, substitution, and others.
Boolean expressions:
Boolean type is declared with the keyword bool. It has two values that can be accepted - true and false. The default value is false. It is most often used to store the result of calculating logical expressions.


Sample tasks:
1) Create Windows Forms Application which shows the cursor coordinates wen moving on the form. Logically separate the form to for quadrants, depending on that in which quadrant is the cursor, change the title of the form to: TopRight, TopLeft, BottomRight, BottomLeft.

Solutioin:
Create new Windows Form Application project.
Add Label control to the form and name it lCoords.

Double click on the form and in its Load event make the label control not visible:
private void Form1_Load(object sender, EventArgs e)
{
   lCoords.Visible = false;
}
From the form designer select the form go to properties, find and click on the Lightening sign to open the events menu. Find and double click on Mouse Move event:


In the generated event add the following code:
int xMousePoint, yMousePoint;

xMousePoint = e.X;
yMousePoint = e.Y;

lCoords.Text = "X: " + xMousePoint + "\n Y: " + yMousePoint;
Point mousePoint = new Point(e.X + 12, e.Y + 12);
lCoords.Location = mousePoint;
lCoords.Show();

if (e.Y < this.Height / 2)
   this.Text = "Top";
else
   this.Text = "Bottom";

if (e.X < this.Width / 2)
   this.Text = this.Text + "Left";
else
   this.Text = this.Text + "Right";
This code captures cursor coordinates and writes them to the Text property of the Label. The location of the cursor is set to the label control so it can be positioned next to the cursor.
Checks are carried out in which part of the form the mouse cursor is and the corresponding text in the title of the form is displayed if the condition is fulfilled.


2) Create Windows Forms Application which shows the coordinates of the cursor in the title bar of the form. When the cursor is in one of the four angles of the form the title of the form to be changed as follows: Top Left corner or Top Right corner or Bottom Left corner or Bottom Right corner.
Solution:
Create new Windows application project.
Select the form, find and double click on the Mouse Move event. Add the following code to the event:
int xMousePoint, yMousePoint;

xMousePoint = e.X;
            yMousePoint = e.Y;

this.Text = "X: " + xMousePoint + "   Y: " + yMousePoint;
Point mousePoint = new Point(e.X + 12, e.Y + 12);

if (e.X == 0 && e.Y == 0)
   this.Text = "Top Left corner";

if (e.X == (this.Width - 17) && e.Y == 0)
   this.Text = "Top Right corner";

if (e.X == 0 && e.Y == (this.Width - 40))
   this.Text = "Bottom Left corner";

if (e.X == (this.Width - 17) && e.Y == (this.Width - 40))
   this.Text = "Bottom Right corner";

3) Create Windows Forms Application that performs the following string actions: exchange two words separated by a specific separator, validation of strings, regular expressions, anagrams and cryptogram.
Solution:
Create new Windows Forms Application project.
Design the form as shown on the picture:


In “GroupBox “String Functions” and name controls as shown:
  • TextBox – tbName;
  • Label1 – lGreetings;
  • Button – bSayHi.

Double click on the button, and its click event add the following code:
string ch;
string digits = "0123456789";
bool ok = true;

tbSocSecNum.Text = tbSocSecNum.Text.Replace("-", "");

if (tbSocSecNum.Text.Length < 9 || tbSocSecNum.Text.Length > 9)
   ok = false;
else
{
   int i = 0;

   while (i < 9)
   {
      ch = tbSocSecNum.Text.Substring(i, 1);

      if (!digits.Contains(ch))
         ok = false;

      i++;
   }
}
lSocSecNumShow.Text = ok.ToString();

The code checks if the entered value in the text box is number with nine characters length. If not a bool variable is set to false. If length is nine characters then a loop is created to check if each of the digits in the number is valid. If not valid then the bool variable ok is set to false. At the end the label text is set to the bool value.
In GrupBox „Regular Expressions” and name controls as shown:
- TextBox – tbSocNum;
- Label3 – lSocNum.
Select the TextBox control, find the KeyPress event and double click on it. Add the following code:
if (e.KeyChar == (char)Keys.Enter)
{
   string soc = tbSocNum.Text;
   Regex socReg = new Regex("[0-9]{9}");
   Match m = socReg.Match(soc);

   if (m.ToString() == soc)
      lSocNum.Text = soc + " - is А \nvalid social security number";
   else
      lSocNum.Text = soc + " - is NOT a \nvalid social security number";
}
The same check as above is done with regular expression.
In GrupBox „Anagrams” and name controls as shown:
  • TextBox – tbWord;
  • Label4 – lAnagram.

Open the source code file and add the following functions under the form constructor.
private string[] SplitString(string sWord)
{
   int iI;
   string[] sLetters = new string[sWord.Length];

   for (iI = 0; iI < sWord.Length; iI++)
      sLetters[iI] = sWord.Substring(iI, 1);

   return sLetters;
}
private void Shuffle(string[] sLetters)
{
    int iI, iP;
    string sTemp;

    Random rndLetter =new Random();

    for (iI = 0; iI <= sLetters.Length - 1; iI++)
    {
        iP = rndLetter.Next(sLetters.Length);
        sTemp = sLetters[iI];
        sLetters[iI] = sLetters[iP];
        sLetters[iP] = sTemp;
    }
}
private string Compress(string[] sLetters)
{
   int iI;
   string sS = "";

   for (iI = 0; iI < sLetters.Length; iI++)
      sS = sS + sLetters[iI];

   return sS;
}
In the KeyPress event of the text box add the following code:
string[] sLetters;
string word = tbWord.Text;

if (e.KeyChar == (char)Keys.Enter)
{
   sLetters = SplitString(word);
   Shuffle(sLetters);
   lAnagram.Text = Compress(sLetters);
}
In GrupBox „Cryptograms” and name controls as shown:
  • TextBox1 – tbWords;
  • TextBox2 – tbCryptogram;
  • Button – bMakeCryptogram.

Add the following function:
private string Scramble(string sS)
{
   int iI;
   char[] chChar;
   chChar = sS.ToCharArray();

   Random rndRandom = new Random();

   for (iI = 0; iI < chChar.Length; iI++)
   {
      int iRandom = rndRandom.Next(25);
      char chTemp = chChar[iI];
      chChar[iI] = chChar[iRandom];
      char check = chChar[iRandom];
      chChar[iRandom] = chTemp;
   }

   string sS2 = "";

   for (iI = 0; iI < chChar.Length; iI++)
      sS2 += chChar[iI];

   return sS2;
}
In the KeyPress event of the text box add the following code:
string sAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string sCode = Scramble(sAlphabet);
this.Text = sCode;
string sS = tbWords.Text;
sS = sS.ToUpper();

string sS2 = "";
int iI, iPos;

for (iI = 0; iI < sS.Length; iI++)
{
   string sChar = sS.Substring(iI, 1);
   iPos = sAlphabet.IndexOf(sChar);

   if (iPos >= 0)
      sS2 += sCode.Substring(iI, 1);
   else
      sS2 = sChar;
}
tbCryptogram.Text = sS2;
Self-assignments
1. Create Windows Forms Application “Age calculator” which calculates the age in years and mounts. Develop the application in two ways:
  • With 3 text box controls and one button; 
  • With DateTime picker. 
2. Create Windows Form Application “Guess the number” in which a random number is chosen every time the application is started. Construct the form with one TextBox control and one Button. When the user enters number and clicks the button, a validation I s made if the number is guessed correctly. If not guessed a direction is given to the user to try smaller or bigger number. If guessed a congratulation message is displayed.
3. Create Windows Form Application “String Manipulation” with the following possibilities:
  • Validate the string if entered value contains: capital letters, non-capital letters, dot (.), comma (,), question mark (?), exclamation mark (!). 
  • Validate entered robot name. The name must contain: capital letter, digit, capital letter, digit – D2R2. 
  • Validation if entered word is palindrome: if the word is read in the right or reverse order it is the same - KUUK. 
  • The program must work without buttons.