C# Label Control

Hello everyone, I hope you all are doing great. In today's article, I will guide you about the C# Label Control. I will show you how to deal with label in C Sharp Programming Language. Labels have their own importance in the software development to nominate the input and output fields. You have observed that every software which you have used and with you are familiar have some labels. Such as in the website login forms there are labels too. It's recommended to use the labels in the software to make the user interface rich with the helping material. If you will just use the C# Button, C# TextBox, and C# ComboBox and don't use the C# Labels then your developed software will not be easy to use. In simple words, it won't be user-friendly. So, in order to make it user-friendly, we have to use Labels in our software. So, let's have a look at How to use C# Label Control and How to change its Properties:

C# Label Control

  • We used the C# Label to display the text on the software to give direction for the user.
  • Label control is also used to show the descriptive text such as the notes and warning about the usage of the software.
  • To define the label in C# you have to declare namespace as follows.
System.Windows.Forms

  • You can also add the label from the toolbox and drag the label from the form designer tab.
  • Label1 is the default Name of the very first label which you will use in your application.
  • You can adjust the size on the form by stretch the coordinates.
  • You can change the text from the right panel under the property label.
  • You can also change the text using the below code:
label1.Text = "TEP C# Label Control Example Text";
  • Here's the output of this code:
  • You can do anything with the label box. There are many properties which you can use to manipulate the functionality of simple label.
  • For example, if you want to change the background color of the label then you need to use BackColor property.
  • BackColor Property is used to change the background color, after the equal (=) sign you have to declare that you want to change color by writing the property Color and after dot, you have to write the name of the color which you want to allocate to the background
  • In the below code I have declared the Aqua color for the background, there are many colors which you can be used for the background of the label.
label1.BackColor = Color.Aqua;
  • Here's the output of above code:
  • If you want to change the foreground color or the color of text, then you need to use ForeColor Property.
  • ForeColor is the name of the property which is used to assign the color of the text in the label.
  • Here's the code for it:
label1.ForeColor = Color.BlueViolet;

  • If you want to set the images as the background of C# label then need to use below code:
label1.Image = Image.FromFile("C:\\Users\\Jade\\Pictures\\brownImage.jpg");
  • Image property is used to set the image. You have to use the Image.FormFile method to set the proper path of an image which you want to set.
  • In double quotation write the path and used "\\" to separate the directories, you have to mention the image with the extension. It will generate the following results.

C# Label Events

Let's do some advanced code to improve the interaction level of your application. Now let's study the builtin events which we can apply on our C# Label to improve its functionality. Events are created to perform some functionalities when user will do any specific task. There are several Events which you can use to implement on your label, here are the few of them:
  • Click Event
  • Double Click Event
  • Text Changed Event
  • MouseHover Event
  • MouseLeave Event

There are several more events which we can use, but the main task here is to just give you the basic concept of C# Label. That's why we will focus on most commonly used events.

C# Label Click Event

  • The first event is the Click Event, which will perform when user will click on the label.
  • Let me give you an example, suppose you need to create a program in which you want to surprise someone, so now when someone click on your software then a hidden message shows up. It could be Happy Birthday !! ;)
  • Here's the code for it, you can change the text to anything you want.
private void label1_Click(object sender, EventArgs e)
        {
            label1.Text = "Text Changed";
        }
  • After the default name, you have to write the _Click  and create the method and declare the functionality which you want to perform.
  • You can do any kind of manipulation inside click event.

C# Label Double Click Event

  • This event will occur when user will click twice on the label.
  • Here's the code for it:
 private void label1_DoubleClick(object sender, EventArgs e)
        {
            label1.Text = "Text Changed";
        }
  • After the default name, you have to write _DoubleClick method and declare the functionality which you want to perform. It will occur when user will click twice on the label.

C# Label Text Changed Event

  • This event will occur when the text of the label is changed.
  • Suppose you want to change any value on the application when the text of the label is changed. Then you will use the TextChanged Event.
  • Let me explain it with an example, I have taken two labels.
  • Now the logic is when the text of one label is changed then the other label text should change automatically.
  • For the first label, I will use the _Click Event and _TextChanged Event too.
  • So, now when user will click on the label, the text of label will change because of _Click Event
  • Now, when text is changed, _TextChanged Event will occur and 2nd label text will also change.
  • Here's the code which you should try.
private void label1_Click(object sender, EventArgs e)
        {
            label1.Text = "Text Changed";
        }

        

        private void label1_TextChanged(object sender, EventArgs e)
        {
            label2.Text = "2nd Text Changed";

        }
  • To test the above code you have to drag two labels on your application. Then copy the above code into your application.

C# Label MouseHover Event

  • This event will occur when user will hover the mouse cursor on the label.
  • Suppose you want to change the text when user will hover the mouse cursor on the label.
  • Here's the code for it:
private void label1_MouseHover(object sender, EventArgs e)
        {
            label1.Text = "Text Changed";
        }

C# Label MouseLeave Event

  • This event will occur when the cursor will leave the label.
  • Suppose you want to change the text of label when mouse cursor will leave the label.
  • Here is the code, which will perform this functionality:
private void label1_MouseLeave(object sender, EventArgs e)
        {
            label1.Text = "again Text Changed";
        }
  • By the combination of the above events and methods, you can create your own C# applications with multiple functionalities.

If you are looking to learn more about the C# label control and other features of the C# programming language than you should subscribe our YouTube channel where we have uploaded latest tutorials on C#. Thanks for reading, have a good day !!! :)

C# TextBox Control

Hello everyone, I hope you are doing great. In this article, we will talk about C# TextBox Control. In the previous articles, you have already get familiar with C# Button ControlC# Label Control, this is the sequence of those. In short C# TextBox Control is just same as the other expect some few changing. Before getting started with C# TextBox you must have knowledge of previous concepts. It's not essential but it will give you the edge to understand the advanced elements of C#.

C# TextBox is used to get input from users or it can also be used to display some values to the user. The textbox is a container for text blocks, you can take inputs or show the text as you required in the form of paragraphs. If you used TextBox as the input field then you can only take one line of text as the input but if you want multiple line input then you have to activate the multiple line property of C# TextBox.

You can also change your input field as the password field if you are using the TextBox for password. A user can write input in the textbox and the even user can simply paste the data too in the field. You can also add some advance features like grabbing the copied data automatically when user hover the mouse on the input field, it will be done by accessing the clipboard where the copied data is saved temporarily, but this is the advance feature which we will cover after the basics. So, now let me show you how to use C# TextBox:

C# TextBox Control

  • First of all, you have to drag the TextBox from the toolbox and adjust it on your application form as you wanted.
  • The Default Name of textbox is 'textbox1' which you can change from the right panel under the property tab.
  • You can also change the Text Property inside of the textbox from the property panel, but if you want to change the text runtime or dynamically then you have to code like below.
 textBox1.Text = "TheEngineeringProjects.com";
  • In the above code, it's clearly mentioned that I have declared the Text property as "TheEngineeringProjects.com".
  • Now when you will execute the code, a textbox will appear with the text automatically, as shown in below figure:
  • You can also give the value of the textbox with the help of variables, like store the string in any variable and then passed to the textbox. Code is given below:
string var = "TheEngineeringProjects.com";
textBox1.Text = var;
  • Till now we have seen How to input value into textbox, now we are gonna have a look at how to extract value from textbox.
  • If you want to extract the value from textbox then you have to use below code:
string var;
var = textBox1.Text;
  • By using the above code, you can easily store the value of textbox into any variable and make it reusable for the whole application.
  • You can set the textbox properties with the help of property panel too.
  • If you want to modify the textbox from property panel then the shortcut for that is F4.
  • If you want to change the textbox height and width dynamically then you have to use the below code.
  • One more thing, you can also change its dimensions from the designer tab by just dragging the coordinates of textbox.
textBox1.Width = 250;
textBox1.Height = 50;
  • If you want to change the background color, then below code will help you out:
textBox1.BackColor = Color.Blue;
  • If you want to change the foreground color, then here's the code for it:
textBox1.ForeColor = Color.White;
  • Now when you apply these codes then you will get something as shown in below figure:
  • Now let's have a look at few of its Border styles.
  • There are three types of the border which you can apply.
    • FixedSingle.
    • Fixed3d.
    • None.
  • If you want to change the border style for textbox then you have to use below codes:
textBox1.BorderStyle = BorderStyle.Fixed3D;
textBox1.BorderStyle = BorderStyle.FixedSingle;
textBox1.BorderStyle = BorderStyle.None;
  • Till now we have seen different Properties of C# TextBox, now let's check out few of the events associated with it.
  • Few of these events are keydown or keypress events.
  • In the below code, I have captured the keystroke from the user and after that I have placed a check for the ENTER keystroke.
  • So, whenever you press ENTER in C# TextBox then a Message Box will open up showing "You Pressed Enter".
private void textBox1_keydown(object sender, KeyEventArgs e)
{
   if(e.KeyCode == Keys.Enter)
   {
      MessageBox.Show("You Pressed Enter");
   }
}
  • You can also add some advanced features too like text change event which will occur when user will change the default text.
private void textBox1_TextChanged(object sender, EventArgs e)
{
      label1.Text = textBox1.Text;
}

 
  • If you want to set the maximum length of the text inside textbox then you can also handle this with max length property like below code.
textBox1.MaxLength = 40;
  • Sometimes you have to fix the textbox so that user can't add the value, in short, to make the textbox disable from the input. For this, you have to activate the ReadOnly property as true.
textBox1.ReadOnly = true;
  • In the beginning, I have declared that you can make your text box as the multiline textbox for that you have to activate the multiline property as the following code do.
textBox1.Multiline = true;
  • If you want your textbox as the password type input field then you have to make the characters as the password using below code.
textBox1.PasswordChar = '*';
  • If you want to make your textbox like whenever the user enters any data it will start from the newline then there are two ways to do it, I'm sharing both the codes:
//First Method
textBox1.Text += "your text" + "\r\n";

//Second Method
textBox1.Text += "your text" + Environment.NewLine;
  • Sometimes we use textbox only for integer values, but when the user adds an integer value in the textbox it will consider as the string by default, so we have to convert that into the integer. It's the major concept for which beginners are searching. Here in the below code, you will get the basic idea how to retrieve the integer value from the textbox input.
int i;
i = int.Parse (textBox1.Text);
  • First, we have taken an integral type variable and then parsed the textbox value through integer. Now, we will parse the textbox with float and double using below code:
//String to Float conversion

		float  i;
		i = float.Parse (textBox1.Text);
//String to Double conversion

		double   i;
		i = float.Parse (textBox1.Text);
  • Here we have done with our C# TextBox Control, and elaborate almost every property which we need in daily software development routine.
  • If you practice these properties than you will become able to create your own small calculators and inventory systems.
  • For just conclusion, I'm going to recap all the properties in one chunk of code given below:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Width = 250;
            textBox1.Height = 50;
            textBox1.Multiline = true;
            textBox1.BackColor = Color.Blue;
            textBox1.ForeColor = Color.White;
            textBox1.BorderStyle = BorderStyle.Fixed3D;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string var;
            var = textBox1.Text;
            MessageBox.Show(var);
        }
    }
}
  • You need to drag the textbox and button on your form and then copy the code.
  • When you will execute this code, it will demand any input from you and when you will enter and press the button it will show you the popup message box in which the input text appears.
  • Here's the video which will help you better in understanding C# TextBox control:
So, that's all for today. I hope you have enjoyed today's tutorial on C# TextBox. I will share more tutorials on C# soon. If you have any questions regarding today's tutorial then you can as in comments. Thanks and take care !!! :)

C# ComboBox Control

Hey everyone how are you, hope you are doing great. In this article I will guide you about the C# comboBox. In my previous article, I have explained about C# button control and their features. C# ComboBox is quite similar to button control but its major properties are different. The combo box can hold multiple values at the same time, it's like drop-down box in appearance and you can select any value inside it. Most of the time, combo box is used to give the user multiple selection options. But in signup forms, it's used for country selection where you have to select your country from drop down. You can use combo box according to your requirements.

You can add the combo box from the toolbar and drag it on the form. When you drag that you can set the height and width by just moving the coordinates of combo box field. In other words, ComboBox is a combination of textbox and list box to show the list data as the text.So,now let's have a look at How to control C# ComboBox:

C# ComboBox Control

  • As I have mentioned earlier, drag your ComboBox from the toolbar and drag it on the Main Form.
  • If you have dragged the C# comboBox then add the following code in the main function to add the demo values in your C# combobox list.
  • By using the following code, you can easily insert the values in your combobox, you can do it manually or you can take inputs from the C# TextBox too, it all depends on the situation and development scheme.
comboBox1.Items.Add("The");
comboBox1.Items.Add("Engineering");
comboBox1.Items.Add("Projects");
  • Here's the screenshot of our C# ComboBox having three items which I have inserted using above c# code:

  • ComboBox1 is the default name of the first combo box which you will drag on the windows form. You can change this name from the property panel which is on the right side. Even that you can insert the values from that too inside the combo box.
  • Every value which you want to insert is considered as an item. You have observed in the above code we used the default.items.add("DataValue") this is the basic syntax for insertion and CRUD is also applied by this syntax.
  • Now move on some advanced techniques which you can be used to make your application more interactive. Like you can be retrieved the selected items from the combo box as the value or input. You just have to take the string type variable and passed the selected item's value to it, you can do this by the following code.
var item = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
  • If you want to show a message box which will be notified you that, what the item you have selected from the combo box. Then you just have to add the message box and used its attribute show to express the values, here is the code below which is working fine and you can test it in your application too.
var item = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
MessageBox.Show(item);

We have inserted the values in above codes, now move on to how we can delete or remove the inserted values. As we used the Add attribute to inserted the values now we will use the Remove and RemoveAt to delete the values. These are the two attributes which we can be used for the same purpose. The first attribute will remove the values directly like you have added the value "Name" then you can delete is as Remove("Name") and the second method is RemoveAt which will remove the value by index like RemoveAt(1) if you don't get the concept, then check the example code below.

comboBox1.Items.RemoveAt(1);

comboBox1.Items.Remove("The Engineering Projects");

You can even change the properties of dropdown by using the DropDownStyle property. It's used to determine that what you actually wanted, mean, are you wanted to show the list always or the data is displayed in a list. You can also edit the text alignment inside of the list.

There are three values which you can be used for the DropDownStyle Property.

  • Simple
  • DropDown
  • DropDownList

You can check the following code where I have shared how you can use these properties, don't copy all the properties to run them at once. Because the last property will get override on all above two properties. So always do code with precautions.

comboBox1.DropDownStyle = ComboBoxStyle.Simple;
comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

You can set the default selected item in the combo box by declaring the SelectedItem property. There are two ways, one you can set it by SelectedItem or you can do by passing the value as FindStringExact. Let's move on code and understand the concept behind these two properties.

comboBox1.Items.Add("The");
comboBox1.Items.Add("Engineering");
comboBox1.Items.Add("Projects");
comboBox1.SelectedItem = "Projects";

In the above code we have inserted three values and by SelectedItem we passed the value which we want to set as the default in a combo box. Let's view the below code which is the second method.

comboBox1.Items.Add("The");
comboBox1.Items.Add("Engineering");
comboBox1.Items.Add("Projects");
comboBox1.SelectedIndex = comboBox1.FindStringExact("Projects");

In this method, we have used the SelectedIndex property and passed the string value by parsing them from FindStringExact method. This is the alternative technique to set the combo box selected item and difficult to remember. You can use them both but the first is easy to remember and understand.

You can also retrieve the database values in a combo box, by using the DataSource property. Let's check the code below how we retrieve the database values in Combo Box.

comboBox1.DataSource = datasetVariable.Tables[0];
comboBox1.ValueMember = "databaseTable_ID";
comboBox1.DisplayMember = "databaseTable_NAME";

We have to use the DataSet variable to retrieve the values from a database, then we will pass that values to DataSource property of C# ComboBox. ValueMember will store the ID values and DisplayMember stored the values of Names, just suppose a SQL query it's same like that. Such as "SELECT databaseTable_ID, databaseTable_NAME FROM StudentsTable".

If you want to manipulate the data between two C# comboBox then you can do easily. Suppose you have taken two combo box and wanted that when you select any value in the first combo box then the value of second combo box gets changed according to the first combo box. Then you have to use the SelectIndexChanged Event. Let's create the code to demonstrate the concept.

using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("TEP Arduino Projects");
            comboBox1.Items.Add("TEP C# Tutorials");
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBox2.Items.Clear();
            if (comboBox1.SelectedItem == "TEP Arduino Projects")
            {
                comboBox2.Items.Add("Stepper Motor Direction Control");
                comboBox2.Items.Add("Stepper Motor Speed Control");
            }
            else if (comboBox1.SelectedItem == "TEP C# Tutorials")
            {
                comboBox2.Items.Add("How to use C# Comments");
                comboBox2.Items.Add("How to add C# Control in Windows Form");
                comboBox2.Items.Add("How to use Button in C# Windows Form");
            }
        }
    }
}

Before using this code, you have to drag two C# combobox on your form and don't change their name. Then go to the main code and replace that with the above code and execute. The first C# combobox gives you two options in the list as TEP C# Tutorials and TEP Arduino Projects. When you selected any of these values the second combo values get changed. Such as if you selected TEP C# Tutorials then the second combo box will show the values as below.

  • How to use C# Comments
  • How to add C# Control in Windows Form
  • How to use Button in C# Windows Form

But if you selected the TEP Arduino Projects then the second combo box value is as follows.

  • Stepper Motor Direction Control
  • Stepper Motor Speed Control

By this, you can create innovative software and give maximum utilities to a user. This is the simple example of multiple combo boxes to give the better understanding of the concept, you can make more advanced code than the above.

You make your combo box unable for a user to give input. Sometimes we need to block the combo box on some conditions. Like combo box will not become enabled until a user will not fill some pre-check statements. There are two ways by which we will change the combo box to read-only. The first way is by changing the DropDownStyle to DropDownList. It will allow users to just read the data but a user will not able to insert any kind of data. The second method is to completely disable the combo box for a user by make the Enable property to false.

First Method:

comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

Second Method:

comboBox1.Enabled = false;

Let's revised all above concepts once again and summarize then in one code. There are much more functionalities which we don't share right now. Because that each function is the whole new concept, such as the OLED or different types of databases which you can connect with your application and the different method of retrieved the data.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("one");
            comboBox1.Items.Add("Two");
            comboBox1.Items.Add("Three");
            comboBox1.Items.Add("Four");
            		comboBox1.SelectedIndex = comboBox1.FindStringExact("Two");

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string var;
            var = comboBox1.Text;
            MessageBox.Show(var);
        }
    }
}

In the above code first, drag the combo box and button on your application and copy the code for execution. When you will execute the code it will allow you to select any item from the list and by default Two is selected. When you click the button it will show you the message with the value of selected item from C# combobox.

Here is the screenshot of C# comboBox Code. You can observe which libraries you have to use for testing the codes.
  • The below video will give you better explanation of C# ComboBox:
So, that's all for today. I hpe you have enjoyed this C# combox Control and can easily implement it in your project. Let me know if you have any problem in it. Have a good day. Take care !!! :)

How to use C# if else Statement

Hello friends, I hope you all are fine and having fun with your lives. Today, I am going to show you How to use C# if else statement. Previously we have seen the Introduction of C# Windows Forms an then we have also discussed different data types and variables used for programming in C#, you can read these tutorials on C# Tutorial page.

So, before starting this C# if else tutorial, I would suggest you to first read all of those basic C# tutorials so that you know how to use different data types. Before starting this tutorial, you should also read How to add C# Control in Windows Form because we are gonna use three C# controls in this tutorial.So, let's get started with How to use C# if else statement:

How to use C# if else Statement ???

  • First of all, let's have an overview of C# if else statement.
Overview
  • If Else Statements are named as conditional logic.
  • C# If statements are essential for any kind of project , IF statement is the most basic conditional logic of C# and is used in almost every project.
  • It acts as if and then you have to specify some statement which is a check statement. In simple words it acts as if this condition is true then do this task. :)
  • Let's have a look at its pseudo code:

IF ( Condition is TRUE )  ====>  Then do this TASK.     

  • Now let me give you an example suppose you are designing some calculator then it must have some buttons on it like Multiply.
  • And you want to multiply any two integers when you click this MULTIPLY button.
  • Now in your code you need to add something like:

IF ( MULTIPLY button is pressed ) ====> Then multiply the two Integer variables

  • So, you can see in the above C# IF statement that clicking of MULTIPLY button is the condition and the multiplication of two integers is the TASK.
  • This C# IF Statement is making the relation between the Condition and the Task.
  • So, now let's have a look at the real C# IF Statement syntax:
C# IF Syntax
  • In C# IF Statements, first of all we place the word "IF".
  • After that, we place the condition in small brackets ( ), the condition must be a comparison which should be either true or false. We will shortly have a look at some example.
  • Now after specifying the condition, next thing we need to do is to specify the task, which comes in curly brackets { }.
  • So, the overall if statement looks something as shown below:
If ( CONDITION comes here ) { TASKS are specified here. }
  • Now, I hope that you have got the complete understanding of this C# IF Statement so let's design a simple example so that I can show you How to use this IF Statement.
Example
  • Now let's design a simple C# Windows Form application and add some Control in it.
  • I have added one Button, one TextBox and one Label and it looks like as shown in below figure:
  • Now I have created a small IF condition that if TEP is written in the Text box then the Label Text will be changed to My Blog.
  • Its just a random logic but quite simple so I thought that it will better explain the logic.
  • So, when you click this button then if TEP is written in the Text Box then we will get My Blog as shown in below figure:
  • You can see in the above figure that when I click the button then it checked the textbox and because TEP is written there that's why Label text is changed to My Blog.
  • Here's the code for the button click function which is quite simple:
if (txtClick.Text == "TEP")
{
    label1.Text = "My Blog";
}
  • So, that's our IF logic as I discussed earlier the condition is in ( ) small brackets and then in curly brackets { } we have our task.
  • But there's a little problem in above condition that I have mentioned to display My blog on TEP but I haven't mentioned what to type when there's no TEP in Text Box.
  • So, what should happen when there's something else in Text box.
  • That's where we encountered with ELSE Statement.
  • In ELSE we specify that TASK which will occur when IF condition is FALSE.
  • So ,let's change our code a little:
if (txtClick.Text == "TEP")
{
   label1.Text = "My Blog";
}
else
{
   label1.Text = " NOT my Blog";
}
  • Now you can see in the above code that I have added the ELSE statement, in which I have mentioned that Not my Blog.
  • So, now when the IF condition is TRUE then Label text will be My Blog and when its FALSE then ELSE will work and we will get NOT My Blog.
  • Check the below image:
  • So, that's how C# if else statement works.
That's all for today. I hope you have enjoyed today's tutorial. I will cover more conditional logic in the coming tutorials. Till then Take care and have fun !!! :)

How to use C# ArrayList

Hello friends, I hope you all are fine and having fun with your lives. In today's post, we are gonna have a look at How to use C# ArrayList. I am gonna explain it in detail what is C# ArrayList and how to use C# ArrayList. But before going into the details of today's tutorial, you must first have a look at my previous tutorial which is How to use C# Array??? because C# ArrayList is quite similar to C# Array.

I am gonna use the same project which we have designed in our first lecture on C# named as Introduction to C# Windows Forms. So, you should also use the same project and as we know this project has one Button and one Text box. Just a recall that I have changed the Text of the button to Click Here and the name of the button to ClickHere. Similarly, I have changed the name of the text box to txtClick. Here's the image of that form:

So, let's continue with How to use C# ArrayList. :)

How to use C# ArrayList ???

Before going into the details of using C# ArrayList, let's first have a look at its definition i.e. what is C# ArrayList and why we have to use it.

What is C# ArrayList ?
  • C# Arraylist is like a bucket which is used to store data in it just like C# Arrays but there's a slight difference between the two. In C# ArrayList you can add or delete data at any time and the ArrayList adjusts itself automatically.
  • Addition or deletion of data in C# ArrayList is done by using indexes of those datas. So, when you add some data in it then the ArratList automatically got stretched and welcomed the incoming data in a new index. :) Similarly when you delete some data from the ArrayList then it shrinks and adjusts the data accordingly.
  • We are shortly gonna have a look at How to add or delete data in c# ArrayList and how it behaves.
  • Now you can see C# ArrayList is quite similar to Array with a slight difference.
  • C# ArrayList is used in old C# Programming but its kind of neglected in new C# Applications because in complex codes it becomes quite messy so the coders normally neglect it and use the alternative but if you have an encounter with any old C# Project then there's a big chance that you find C# Arraylist in it.
  • Now, let's have a look at how to initialize an ArrayList:
Initializing a C# ArrayList
  • In order to initialize a C# ArrayList, you have to use the below code:
// .... Initialization of C# ArrayList .....

     ArrayList TEP = new ArrayList();

// .... Ends Here ......
  • Now in the above code line you can see I have used the ArrayList as a datatype and then I have given my variable a name, which is TEP.
  • So, in simple words, I have created a ArrayList named TEP.
Note:
  • One important thing is you have to add using System.Collections; in the top section of your code otherwise system won't recognize the keyword ArrayList.
Adding Data to C# ArrayList
  • Now, let's add some data in our C# ArrayList, which we just created in the above section.
  • In order to add the data, we have to use the command TEP.Add(), where TEP is the name of our ArrayList while our data comes in the brackets.
  • So, let's add some data in our C# ArrayList by using the below code:
// .... Adding Data in ArrayList ....

     TEP.Add("The");
     TEP.Add("Engineering");
     TEP.Add("Projects");

// .... Data added in ArrayList ....
  • So, I have added three values in my TEP ArrayList.
  • Now, let's print them out.
  • So, in your Button Click function add the below code:
// ... Displaying values .....

     txtClick.Text = TEP[0].ToString();
     txtClick.Text += " , ";
     txtClick.Text += TEP[1].ToString();
     txtClick.Text += " , ";
     txtClick.Text += TEP[2].ToString();

// ... Values Displayed .....
  • In the above code, you can see I have called those values via their indexes.
  • Now your complete code will look something as shown in the below figure:
  • Now, in the above figure, you can see all the three steps i.e. initialization of C# ArrayList, then adding values in that ArrayList and finally displaying those values.
  • Now, when you click run your program and then click the button you will got your C# ArrayList in the text box as shown in below figure:
  • And you can see in the above figure that our TEP ArrayList elements are printed in the text box.
ArrayList Elements Count
  • Now, let's have a look at how to count the total number of elements in an ArrayList.
  • In order to do so, you have to add a small code in your button click function as given in below code:
// .... Display Values .....

      txtClick.Text = TEP[0].ToString();
      txtClick.Text += " , ";
      txtClick.Text += TEP[1].ToString();
      txtClick.Text += " , ";
      txtClick.Text += TEP[2].ToString();
      txtClick.Text += " , ";
      txtClick.Text += TEP.Count;

// ..... Values Displayed .....
  • You can see in the above code, I have added a small function to display the TEP Count and when you run it, it will show you the total values in your ArrayList as shown in below figure:
  • Now you can see the last figure is showing the total number of elements in that ArrayList.
Clearing a C# ArrayList
  • Now suppose you have created a C# ArrayList and now you wanna clear its values then you have to use a simple clear command as shown in below code:
      txtClick.Text = TEP[0].ToString();
      txtClick.Text += " , ";
      txtClick.Text += TEP[1].ToString();
      txtClick.Text += " , ";
      txtClick.Text += TEP[2].ToString();
      txtClick.Text += " , ";
      txtClick.Text += TEP.Count;
      TEP.Clear();
      txtClick.Text += " , ";
      txtClick.Text += TEP.Count;
  • In the above code, first of all, I have displayed the values of ArrayList and after that I have displayed the total elements in that ArrayList and then I cleared the ArrayList using TEP.Clear(); and then again displayed the total elements and because I have cleared the ArrayList that's why it will give you 0 this time because now there's no element in it as shown in below figure:

Now, I hope that you are well aware of ArrayList and can easily use it in your program if you have to. So, that's all for today, will see you guys in the next tutorial. Till then take care and have fun !!! :)

How to use C# array

Hello everyone, hope you all are fine and having fun with your lives. In today's tutorial, we are gonna have a look at How to use C# Array. C# array is quite a simple concept but students normally got confused while using C# array that's why I am gonna explain it in a detail. C# array is used to store similar data in a single variable. Let me explain this with an example. Suppose you have 10 integer variables then what you need to do is to save all of these 10 variables in separate C# Int variables which will not only increase the size of your code but will also make it quite complex. So, instead of creating 10 separate C# Int variables you can simply create a single C# array and can add all of them in it.

Let's take an example for C# arrays from normal life. You can consider a classroom of a school as an array and its elements will be all the students in that class. :) So, if there's a 9th class then all the students in 9th class are the members of that 9th class array but the students of 10th class will not be members of 9th class array, instead they will be members of 10th class array. :P Now, a question arises that how to call a single member of any array then in that case for class arrays we have roll numbers. so you can call any member of 9th class by calling his roll number. Similarly, in C# array we have indexes for each member of an array and we can call individual members using these indexes, we will have a look at it below. The members of any arrary are normally called the Elements of that array. So, let's get started with C# arrays.

You may also like:

How to use C# Array ???

  • As I explained earlier, C# Array is used to store similar variables in it. So, instead of using individual variables, we can simply add all those similar variables in a single array.
  • So, an array is something as shown in below figure:

FirstArray[3] = {Element1, Element2, Element3};

  • Now the above array has a name FirstArray and it can has maximum three members in it which is shown in these [ ] brackets.
  • After that we have inserted the three members in it separated by commas.
  • Now, if I want to access the individual members of this C# Array then I have to call them by their indexes.
  • C# Array assigns an index to each of its elements and these indexes start from 0.
  • So, the first element of each C# Array is always 0.
  • So, if I call the 0th member of C# array then it will give me the first element of that array.
  • Let's see how to call each of them:
  • FirstArray[0] = Element1;
  • FirstArray[1] = Element2;
  • FirstArray[2] = Element3;
  • So, that's how we can call any of the C# Arrays elements.
  • Now let's design a simple projects and check it out in real example.
  • So, create a simple C# project as we did in Introduction to C# Windows Forms.
  • Now in this C# projects add some controls as we did in How to add C# Control in Windows Form.
  • I have added two controls in it which are Button and a Text Box.
  • The simple GUI is shown in below figure:
  • So, now let's add an array in this GUI and then display its elements in the text box on button click.
  • I am gonna add a C# string array so first of all, what I need to do is to declare the String C# array.
  • In order to do so use the below code:
// C# Array Initializing

String[] students = new String[5];

// Initializing Complete
  • So, you can see in the above code that I have initialized the C# array and in order to do so first of all, I have given the datatype of C# Array, which is String in the above case.
  • After that, I have given the name of the C# Array which is students and the I have used new word to create the new instance of C# array.
  • We will cover this new word concept in later tutorials but rite now its necessary to use it while initializing the C# array.
  • Finally I have given the length of array which is 5 in our case, so you can add maximum 5 elements in this C# array.
  • You can also make the length variable by simply removing this 5 as shown in below code:
// C# Array Initializing

String[] students = new String[];

// Initializing Complete
  • Now this C# String Array is of variable length means you can add any kind of members in it.
  • Now we have initialized our C# String Array, next thing we need to do is to add the values in it.
  • One way of adding values to the C# array is as follows:
// Adding values to C# Array.

students[0] = "Zain";
students[1] = "Nasir";
students[2] = "Kamraan";
students[3] = "John";
students[4] = "Jack";

// Values added.
  • Now you can see I have added five students in our C# Array and I have also assigned the index to each of them.
  • "Zain" is saved at index 0 of students array so it will be the first element of C# array.
  • That's one way of assigning values to C# array, here's another way:
// Adding values to C# Array.

String[] students = new String[5] {"Zain", "Nasir", "Kamraan", "John", "Jack"};

// Values added.
  • In the above code, I have added the values in the initialization, both ways are correct.
  • Now let's get the elements from this array and display them in the Text Box.
  • In order to do so, use the below code:
txtClick.Text = students[0];
txtClick.Text += " , ";
txtClick.Text += students[1];
txtClick.Text += " , ";
txtClick.Text += students[2];
txtClick.Text += " , ";
txtClick.Text += students[3];
txtClick.Text += " , ";
txtClick.Text += students[4];
  • One thing, I forgot to mention that I have changed the Name of the Button to ClickHere and Text of Button to Click Here. Moreover, I have changed the Name of Text Box to txtClick.
  • Now your complete code will look something as shown in below figure:
  • Now run your project and click the button and if everything goes fine then you will get results as shown in below figure:
  • So, you can see all the elements of our C# Array are now displayed in the Text box.
So, that's all about the C# Arrays, I hope you guys have got something out of it. That's all for today, will meet you guys in the next tutorial. Till then take care and have fun !!! :)

How to use C# Comments ???

Hello everyone, I hope you all are fine and having fun. Today's tutorial is a quick one and is about how to use C# Comments. Comment is an important part of any programming language, although its not a directly part but they indirectly help a lot especially in complex projects.

I have also shared a tutorial on How to use comments in c++, you should read that post as well because I have explained few basic concepts in it. You guys are also welcome to give us feedback about this new C# tutorial series. If you have any suggestions about it then do let us know in comments.

How to use C# Comments ???

  • Comments are simple documented text lines, completely ignored by the compiler and are used to explain or provide any additional information about coding.
  • There are 3 types of comments available in C#, which are:
    • Single Line Comments. ( Symbol used: // )
    • Multi-Line Comments. ( Initial Symbol: /* Closing Symbol */ )
    • XML Documentation Comments. ( /// )
  • Now, let's have have look at each one of them in detail:

Single Line Comments

  • Single Line Comments are used to comment any text in a single line, we have to place two forward slashes ( // ) and everything after that will be ignored by the compiler.
  • Let's have a look at How to use Single Line Comments, in below figure:
  • You can see in above figure, that I have used green comments above each block to explain my code i.e. mentioning 2D & 3D arrays, accessing array elements etc.
  • Moreover, I have also used comments in front of the line i.e. displaying data at location 0, 0 etc. In this case, I am just explaining a single line.

Multi-Line Comments in C#

  • We can also comment out multiple lines by using /* */ these symbols.
  • Let's say, you don't want to execute some part of your code i.e. 100 lines, then it would be too difficult to place // these symbols in front of each line.
  • In such cases, there's a need for Multi-Line Comments, here's an example:
  • At the top of above code, you can see I have used Multi-Line Comments to give a simple introduction, here you can also add description of your project/code.
  • Moreover, I have also commented out Console code, I just want output using For Loop and I have used Multi-Line Comments for that.

XML Documentation Comments

  • In Microsoft Visual Studio, when you hover your cursor on any object then it pops up an info box.
  • If you want to add any information in this pop up box then you need to use XML Documentation Comments, as shown in below figure:
  • In the above code, I have created a new class named TEPClass, we will discuss classes later in detail, but for now just focus on XML comment above that class.
  • In Program class, I have called TEPClass and now when I hover my cursor over it, you can see a pop up box appeared and it has that XML comment in it.
  • I have placed a red arrow in front of it, here we can place a short description of our class.

Why we need to use C# comments ???

  • Let's say you have to use some old code which you have designed a year ago.
  • Now when you read your own code after a year, it will be difficult to understand.
  • But if you have placed some check note (comments) for each command then you can easily understand it.
That's all for C# comments. I hope you guys have understood how & why we need to use C# Comments. In next tutorial, we will have a look at How to use If Loop in C#.

How to use C# String Variables

Hello friends, I hope you all are fine and having fun with your lives. In today's tutorial, we are gonna have a look at How to use C# String Variables in your C# Projects. In the previous tutorials, we have a look at How to use C# Int Variables and also have seen How to use C# Double Variable. So, now today we are gonna see how to use C# String Variable.

We have already discussed the variables in detail so I hope that you must have the idea of what variables are and if you don't then you must read the previous tutorials first. The code is also given below in the tutorial. So, let's get started with How to use C# String Variables:

How to use C# String Variables ???

  • C# also supports string variable, a string variable can save anything in it in the form of characters.
  • C# String variable can be of any length.
  • So, let's design a small code to show how C# String works.
  • First of all design a simple C# Project and add one button and one text box in it, as shown in below figure:
  • Now change the Text of your Button to Click Here and Name of the button to ClickHere.
  • Similarly change the Name of the text box to txtClick.
  • We have already designed a similar project in How to use C# Int variables.
  • Now that our project is added so now add the below code into it an your code will look something like:
  • Now you can see in the above figure, that first I have created a string variable named webBlog.
  • After that I have assigned it a value, because the variable is a C# string variable that's why it can save this string easily in it.
  • After that I have simply displayed it in that text box.
  • You must have noticed that this time we didn't have converted the value to string as we did in C# Double variable.
  • Because our variable is already a string.
  • Here's the complete code for copying:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Variables
{
    public partial class Form1 : Form
    {
        string webBlog;
         

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void ClickHere_Click(object sender, EventArgs e)
        {
            webBlog = "www.TheEngineeringProjects.com";
            txtClick.Text = webBlog;


        }
    }
}
  • Now let's have a look at the results.
  • So, run your project and then click on the button and the string will appear in the text box as shown in below figure:
  • So that's how C# string variable works.
  • Now you can save any kind of long strings in C# string variable.
  • Now let's have a look at few of the string properties.
C# String Comparing
  • Suppose you have two strings then How to compare them.
  • So write your code as shown in below figure:
  • Now you can see in the above code, I have used two C# String variables webBlog1 and webBlog2.
  • I have given the same text to both of these C# string variables.
  • Now after that I have used a small function called String.Compare() and it takes two C# string variables.
  • After that it compares these two C# string variables and if they are same then it give 0 so that's why I have compared it to 0 means if the two C# string are equal then I have printed Both are equal otherwise not equal.
  • So, that's how you can compare two C# String Variables.
  • Here's the code for copy:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Variables
{
    public partial class Form1 : Form
    {
        string webBlog1, webBlog2;
         

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void ClickHere_Click(object sender, EventArgs e)
        {
            webBlog1 = "www.TheEngineeringProjects.com";
            webBlog2 = "www.TheEngineeringProjects.com";
            if (String.Compare(webBlog1, webBlog2) == 0)
            {
                txtClick.Text = "Both are equal";
            }
            else
            {
                txtClick.Text = "Both are not equal";
            }


        }
    }
}
Find subString in C# String
  • Now suppose you have a long string and you want to find some small string whether its in the long string or not.
  • Then you can use another function named as contain and the below example shows how to use this command:
  • In the above figure, you can see that I have initialized a C# String variable and given it a string text.
  • After that I have used the function String.Contain and checked a part in the string.
  • So you can see the String is actually in the main string so it will give Its present in the string otherwise not present.
  • So, run your project and then click the button and you will get something as shown in below figure:
  • Now, you can see it has given that its present in the string.
  • Here's the code for copying:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Variables
{
    public partial class Form1 : Form
    {
        string webBlog1, webBlog2;
         

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void ClickHere_Click(object sender, EventArgs e)
        {
            webBlog1 = "www.TheEngineeringProjects.com";
            if (webBlog1.Contains("Projects"))
            {
                txtClick.Text = "Its present in string";
            }
            else
            {
                txtClick.Text = "Its not present in string.";
            }


        }
    }
}
Dividing a C# String
  • So, now let's get something out of a string.
  • Suppose in some project you have a very long C# string and you just want a part of that C# string.
  • Then what you need to use is another string command which is webBlog1.Substring(4).
  • So, have a look at the below code:
  • Now in the above code you can see I have initialized a C# String variable and assigned it a value.
  • After that, I have used second variable and then I have subString it by four characters and now run your project and click the button and you will get results as shown in below figure:
  • So, you can see in the above string I have subString four characters in the initials and then the remaining is shown in the text box.
  • So, that's how you can take any number of subString from the C# String.

So, that's all about C# String Variable. I hope you guys have learned something out of it. that's all for today. In the next tutorial we will learn more about C#. Till then take care and have fun !!! :)

How to use C# Double Variables

Hello friends, hope you all are fine and having fun with your lives. Today, I am going to show you guys How to use C# Double Variable in your projects. In our previous tutorial, we have seen How to use C# Int Variable and we have also discussed about the term Variables in detail. So, I am not gonna discuss it again and gonna come straight to our topic C# Double variable. It's my second C# tutorial in the series of C# variables. In the coming tutorials, I will discuss the remaining C# variables in detail. I have also provided the project code below but I would suggest you to do it on your own so that you get most out of it.  Moreover, you should also have a look at Introduction to C# Windows Forms and How to use C# Control in Widows Forms as I am gonna use two C# Controls in today's tutorial as I did in C# Int tutorial. So, let's get started with How to use C# Double Variable:

How to use C# Double Variable ???

  • C# double variable can store 64 bit value in it.
  • C# double can store integer as well as decimal values means you can save decimal values like 5.2, 3.1 as well as simple integers like 2, 5, 38 etc.
  • C# double variable approximate value is ±5.0 × 10^-324 to ±1.7 × 10^308 as per Microsoft Official Page and its precision is 15-16 digits.
  • So, first of all, design a new simple C# project as we did in Introduction to C# Windows Forms.
  • I am not gonna design a new one, instead I am gonna use the same project as I did for C# Int Variable.
  • So after creating a new project, add a Button and a Text Box in it as we did in How to add C# Controls in Windows form.
  • Now, I hope that you are done with the front end of your C# Project and it will look something as shown in below figure:
  • Now, let's add the code behind this form, so your code will look something as shown in below figure:
  • Now if you have a look at it then you will see that its exactly the same code as we did for C# Int variables.
  • But there's a slight difference that now all of the three variables a, b and c are double instead of int.
  • That's why I have assigned decimal values to them where a = 2.5 while b = 2.6.
  • C# Int variable can't use these value because these are not integers but double can easily handle them.
  • So, now their result should be 5.1 which is again a double so that's why our third variable is also double.
  • Here's the code for you to copy:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Variables
{
    public partial class Form1 : Form
    {
        double a = 2.5;
        double b = 2.6;
        double c;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void ClickHere_Click(object sender, EventArgs e)
        {
            c = a + b;
            txtClick.Text = c.ToString();
        }
    }
}
  • So, now run your project and then click the button and you will get results as shown in below figure:
  • So, now you can see the value saved in C# double variable c was 5.1 which is now displayed in the Text Box.
So, that's all for today. I hope you guys have now understood How to use C# double variables in your projects. Thanks for reading. Have fun and take care. :)

How to use C# Int Variables

Hello friends, hope you all are fine and having fun with your lives. Today, I am going to share a new tutorial on C# language which is How to use C# Int variables. In our previous C# tutorials, we have designed a small project in C# which prints Hello World on the screen. Then we have seen Introduction to C# Windows Form, in which we have designed our first Windows form in C#. Then we have added the C# controls on that windows form.

Now, in today's tutorial, I am gonna introduce you to a new concept which is variables. Variables are used in every programming language and without variables we can't design even a simple code. There are different types of variables available in C# language and today among these variables we are gonna focus on C# Int variables. If you are doing engineering then you must have the idea about integers. :P So, let's get started with C# Int variables. Before discussing the C# Int variables, let's first get an overview of variables.

What are Variables ???

  • In any kind of programming projects, there's a need for storing some data in temporary memory spaces. these temporary memory spaces are named as variables.
  • For example, I have a simple project in which I need to add 2+2 and then I need to add 2 more in the output.
  • So, in that case what I am gonna do is first of all, I am gonna do the simple addition operation and will add the 2+2 and then I need to save the output which is 4 somewhere.
  • So, I am gonna save this output 4 in a variable and then I am gonna add 2 more in that variable and again I will save the output which is 6 in another variable and then I can print it on the output.
  • I think now its quite clear from the above example that variables are used to store data for a short time.
  • Now data can be of any type, it could be an integer or some decimal value or it could be characters.
  • So, that's why we have a long list of variable types in C#, which are as follows:
  • Int (Integer)
  • Double
  • Float
  • Char
  • String
  • Byte
  • sByte
  • Decimal
  • Boolean
  • You can read more about the variables from Microsoft Variables Page.
We will cover all these variables in separate tutorials one by one and we will see how to use them and to work with them. So, rite now we are gonna have a look at usage of C# Int variable, so let's get started with it.

How to use C# Int variables ???

  • C# Int variables are used for storing integers values. Int is actually a short form of Integer.
  • So, for example, you have to save 2 in some variable then as 2 is an integer so you can save it in C# Int variable.
  • But if you have 2.05 value then its not an integer because it has a decimal part so you can't save this value in an integer so C# Int variable will only save integers in it.
  • Let's design a simple example on C#, as we did in Introduction to C# Windows Forms.
  • Now in this project, I am gonna add a Button and a Text Box and on pressing that Button I will print a variable in this Text Box.
  • So, design a simple project, as shown in below figure:
  • I have changed the name of the Button to "ClickHere" and the Text of the Button to "Click Here".
  • I have also changed the Name of the Text Box to "txtClick".
  • Now add some code in the Button as shown in below figure:
  • In the above code, you can see first of all I have declared the C# Int variables, which are a, b and c.
  • Then I have also assigned a value to a and b, which is 2.
  • Now in the Button Click function, I have added both the C# Int variables and then saved their result in another C# Int variable named as c.
  • Finally, I have printed that c variable in a text box.
  • You must be wondering why I have used toString() because text boxes can only print strings but c is an integer so that's why I have converted that integer into string.
  • I will discuss this string conversion in more detail later.
  • Here's the code for you to use:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Variables
{
    public partial class Form1 : Form
    {
        int a = 2;
        int b = 2;
        int c;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void ClickHere_Click(object sender, EventArgs e)
        {
            c = a + b;
            txtClick.Text = c.ToString();
        }
    }
}
  • Now run your project and when you click the button then 4 will appear in the text box as shown in below figure:

So, I hope now you have got the idea How to use C# Int Variables. That's all for today. You should also have a look at How to use C# Double Variables. In the coming tutorial, we will discuss other C# variables just like this C# Int variable. Till then take care and have fun !!! :)

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir