Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter Two

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 74

Chapter Two: Basic Window

Forms/Graphical User Interface(GUI)


Part-I

Event-Driven programming
Prepared by:
Ataklti Nguse
2.1 Introduction To GUI
• GUI means Graphical User Interface.
• In C#, the most rapid and convenient way to create your
user interface is to do so visually, using the Windows
Forms Designer and Toolbox.
• It is the common user Interface that includes Graphical
representation like buttons and icons, and communication
can be performed by interacting with these icons rather than
the usual text-based or command-based communication.
• Windows Forms is a Graphical User Interface(GUI)
class library which is bundled in.
• The .NET framework provides a class library of various
graphical user interface tools such as frame, text box,
buttons etc.
• C# can use to implement a GUI very easily and fast.
Continued…
• . Net Framework is to provide an easier interface
to develop the applications for desktop, tablet,
PCs.

• The following are some of the visual items.


• Form: displays as a window.
• Button: displays a clickable button
• Label: displays a label
• TextBox: displays an area to edit
• RadioButton: displays a selectable button
2.1.1 Windows form
• C# programmers have made extensive use of forms to
build user interfaces.
• Each time you create a Windows application, Visual
Studio will display a default blank form.
 Basically, many programmers have many forms
that are accessible from the main form that loads
at start up
 Each form inherits the properties and methods on
the System.Windows.Forms.Form class.
 The namespace System.Windows.Forms contians
components you will need for creating forms and
controls.
Cont’d

5
Cont’d

 The forms designer allows a programmer to drag and drop controls form a
Toolbox onto form
 If the drop toolbox isn’t visible, you can select it from the view
Toolbox menu.
 The form designer generates code based on the programmer’s drag-drop
actions and property setting
6
Cont’d
 You can modify the properties of controls using the
properties window
 If the properties window isn’t visible, you can select it from the view |
properties window menu
 The properties can be shown by category or alphabetically by selecting
an icon from the properties window toolbar

7
Cont’d

 There aren't many programs that have only one form.


 Most programs have other forms that are accessible from the main one
that loads at start up.

8
Adding form to a project
 To create multiple forms first create the main form
 Next, we’re going to add another form. To do this, here’s the
following steps:
 Go to Solution Explorer
 Right click project and select Add
 Then Choose “Windows Form”
 And it will automatically
add a new form to your project.

9
2.1.2 C# Label Control
• Labels are one of the most frequently used C#
control.
• Label control uses to display text in a set location
on the page.
• Label controls can also be used to add descriptive
text to a Form to provide the user with helpful
information.
• The Label class is defined in the
System.Windows.Forms namespace.
 Drag a label control from the toolbox to the form.

 By default, it will have an initial text.

 A Link Label control is a label control that can display a


hyperlink.
Label Control
• Add a Label control to the form - Click Label in the
Toolbox and drag it over the forms Designer and
drop it in the desired location.
• If you want to change the display text of the Label,
you have to set a new text to the Text property of
Label.
label1.Text = "This is my first Label";
• the Label control can also display an image using the
Image property, or a combination of the ImageIndex
and ImageList properties.
• label1.Image = Image.FromFile("C:\\testimage.jpg");
2.1.3 C# Button Control
• A button is a control, which is an interactive component that
enables users to communicate with an application.
• The Button class inherits directly from the ButtonBase class.
• A Button can be clicked by using the mouse, ENTER key, or
SPACEBAR if the button has focus.
• How to Call a Button's Click Event Programmatically
• The Click event is raised when the Button control is
clicked.
• Raising an event invokes the event handler through a
delegate.
Cont’d
 When you want to change display text of the Button , you can change
the Text property of the button.
 button1.Text = "Click Here";
 Similarly if you want to load an Image to a Button control , you can
code like this
 button1.Image = Image.FromFile("C:\\testimage.jpg");

 The Button controls(System.Windows.Forms.Button) is commonly used

to execute commands when it is clicked.


 When a button is clicked, you specify codes that will be used.

13
2.1.4 TextBox Control
• A TextBox control is used to display, or accept as input, a
single line of text.
• This control has additional functionality including multiline
editing and password character masking.
• A text box object is used to display text on a form or to get
user input while a C# program is running.
• For displaying a text in a TextBox control , you can code like
this.
textBox1.Text = "http://csharp.net-informations.com";
• You can also collect the input value from a TextBox control
to a variable like this way.
string var = textBox1.Text;
C# TextBox Properties
• Textbox Maximum Length
• Background Color and Foreground Color
• Textbox BorderStyle
• Textbox ReadOnly
• Multiline TextBox
• Textbox password character
• How to retrieve non string values from textbox ?
2.1.5 ComboBox Control
• A ComboBox displays a text box combined with a
ListBox, which enables the user to select items from
the list or enter a new value .
• The user can type a value in the text field or click
the button to display a drop down list.
• You can add individual objects with the Add method.
• You can delete items with the Remove method or
clear the entire list with the Clear method.
• Adding item
comboBox1.Items.Add(“Information Systems");
comboBox1.Items.Add(“Computer Science");
comboBox1.Items.Add(“Software Engineering");
ComboBox SelectedItem
How to retrieve value from ComboBox
• If you want to retrieve the displayed item to a string
variable , you can code like this string var;
var = comboBox1.Text;Or
var item =
this.comboBox1.GetItemText(this.comboBox1.SelectedItem)
;
MessageBox.Show(item);
Continued
How to remove an item from ComboBox
• You can remove items from a combobox in two ways.
• You can remove item at a the specified index or giving a
specified item by name.
comboBox1.Items.RemoveAt(1);
• The above code will remove the second item from the
combobox. comboBox1.Items.Remove("Friday");
• The above code will remove the item "Friday" from the
combobox.
2.1.6 Checkbox and Radio Button Control
Check Box
 allows user to make multiple selection from number of options
 It to give the user an option, such as true/false or yes/no
 You can click a check box to select it and click it again to deselect it.

19
Radio Button control
• A radio button or option button enables the user to select a single
option from a group of choices when paired with other
RadioButton controls.
• When a user clicks on a radio button, it becomes checked, and all
other radio buttons with same group become unchecked.
• The RadioButton control can display text, an Image, or both.
• Use the Checked property to get or set the state of a RadioButton.
radioButton1.Checked = true;
• Use a radio button when you want the user to choose only one
option.
• When you want the user to choose all appropriate options, use a
check box. Like check boxes, radio buttons support a Checked
property that indicates whether the radio button is selected.
ListBox Control
• The ListBox control enables you to display a list of items to the
user that the user can select by clicking.
• In addition to display and selection functionality, the ListBox also
provides features that enable you to efficiently add items to the
ListBox and to find text within the items of the list.
• You can use the Add or Insert method to add items to a list box.
• The Add method adds new items at the end of an unsorted list box.
listBox1.Items.Add("Sunday");
• If you want to retrieve a single selected item to a variable , you can
code like this
string var;
var = listBox1.Text;
Cont…
• The SelectionMode property determines how many items in the
list can be selected at a time.
• A ListBox control can provide single or multiple selections using
the SelectionMode property .
• If you change the selection mode property to multiple select ,
then you will retrieve a collection of items from
ListBox1.SelectedItems property.
listBox1.SelectionMode = SelectionMode.MultiSimple;
foreach (Object obj in listBox1.SelectedItems )
{
MessageBox.Show(obj.ToString ());
}
Picture
box
This windows pictureBox control is used to display images
in bitmap, GIF, icon, or JPEG formats

Picture
Box

23
C# ProgressBar Control
 A progress bar is a control that an application can use to indicate
the progress of a lengthy operation such as calculating a
complex result, downloading a large file from the Web etc.

24
C# ScrollBars Control

 A ScrollBar allows you to view content that is outside of the current


viewing area by sliding the Thumb to make the content visible.

25
C# DateTimePicker Control

 The DateTimePicker control allows you to display and collect date


and time from the user with a specified format.

26
C# Treeview Control
 The TreeView control contains a hierarchy of TreeViewItem controls.
 It provides a way to display information in a hierarchical structure by
using collapsible nodes .
 The top level in a tree view are root nodes that can be expanded or
collapsed if the nodes have child nodes.

27
C# ListView Control
 The ListView control is an ItemsControl that is derived from ListBox.

28
C# Menu Control
 A Menu on a Windows Form is created with a MainMenu object,
which is a collection of MenuItem objects.
 MainMenu is the container for the Menu structure of the form and
menus are made of MenuItem objects that represent individual
parts of a menu.

29
NumericUpDow
 n
The NumericUpDown controls is typically used to get numeric inputs and
automatically restricts user for giving invalid non- numeric values.
 The NumericUpDown control appears like a textbox control, but there
are arrow buttons on its right or left side that is used to increment or decrement the
value of the control

30
C# MDI Form

 A Multiple Document Interface (MDI) programs can


display multiple child windows inside them.

31
MonthCalende
r The MonthCalender control presents an intuitive
graphical interface for users to view and set date
information.

32
The ColorDialog
Control
The colorDialog(system.Windows.Forms.ColorDialog) is
used when you want to pick different colors.
 For example, when you want to pick a color of the font or
a background color for the form, you can use the
colorDialog control.
 The following are some of the useful properties of
the ColorDialog control.

33
Cont’
d

34
Cont’
d

35
The FontDialog
Color
The FontDialog control(System.Windows.FontDialog) is
a handy control for selecting different kinds of font.

36
Cont’
d

37
FolderBrowserDialod
Control
 Folder browser is a .NET control that prompts user to
browse and select a folder location.
 Using FolderBrowserDialoge user can only select folders
and not files.
 The FolderBrowserDialog
control(System.Windows.Forms.FolderBrowserDialod
allows browse a folder on your system.

38
Cont’
d
Halu Step 2

Step 1

Step 3

39
Cont’
d

40
OpenFileDialog
Control
An OpenFileDialog control is used to browse and select a
file on a computer.

41
SaveFileDialog
control
SaveFileDialog control is used to save a file using
Windows Save File Dialog.

42
C# Print Dialog Box
 user can use the Print dialog box to select a printer, configure it, and
perform a print job.
 Print dialog boxes provide an easy way to implement Print and Print
Setup dialog boxes in a manner consistent with Windows standards.

43
Part-II
Form Validation and
Database Connectivity
What is form validation?
 Form validation is a “technical process where a web form checks
if the information provided by a user is correct or not.”
 The form will either alert the user that they messed up and need to
fix something to proceed, or the form will be validated and the user
will be able to continue with their registration process.
 There are many types of validation in C# that we can use to validate
the field of any registration form or any other form which takes
inputs or values from the user.
 They are given below.

45
Continued…
•Textbox Validation in C#
•Length Validation in C#
•UserName Validation in C#
•Password Validation in C#
•Email Validation in C#
•Phone number Validation in C#
C# Regular Expressions
• A regular expression defines a search pattern for strings.
• Regex represents an immutable regular expression. It contains
methods to match text, replace text, or split text.
Validation For Alphabetic and
digit only
• "^[.0-9]*$" for digit numbers
• “[a-zA-Z ]*$” For alphabetic ONLY
C# regex email

• In the following example, we create a regex pattern


for checking email addresses.
• @"[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]
{2,18} “
C# regex isMatch
• A regular expression is a pattern that could be matched
against an input text.
• public static bool IsMatch(string input, string pattern)
• Indicates whether the specified regular expression finds a
match in the specified input string.
UserName Validation in C#

• [a-zA-Z] => first character must be a letter


[a-zA-Z0-9] => it can contain letter and number
{5,11} => the length is between 6 to 12
• Password Validation in C#
• Min 6 char and max 14 char
• One upper case
• One special char
• One lower case
• No white space
Continued…
• Min 8 char and max 14 char:
• if (passwd.Length < 6 || passwd.Length > 14)
• return false;
• One upper case:
• if (!passwd.Any(char.IsUpper))
• return false;
• At least one lower case:
• if (!passwd.Any(char.IsLower))
• return false;
Continued…
• No white space:
• if (passwd.Contains(" "))
• return false;
• Check for one special character:
• string specialCh = @"%!@#$%^&*()?/>.<,:;'\|}]{[_~`+=-" +
"\"";
• char[] specialCh = specialCh.ToCharArray();
• foreach (char ch in specialChArray) {
• if (passwd.Contains(ch))
• return true;
• }
To make strong Password
• string pass=textBox6.Text;
• if (string.IsNullOrEmpty(pass) == true)
• {
• MessageBox.Show("Password is empty");
• textBox6.Focus();
• return false;
• }
• string strpass = textBox6.Text;
• if(strpass.Length<5|| strpass.Length > 20)
• {
• MessageBox.Show("*enter pass word length between 6-20");
• textBox6.Focus();
• return false;
• }
• if (!strpass.Any(char.IsUpper))
• {
• MessageBox.Show("*enter pass word atleast one uppercase ");
• textBox6.Focus();
• return false;
• }
• string special = @"%!@#$%^&*()?/>.<,:;'\|}]{[_~`+=-" + "\"";
• char[] specialCh = special.ToCharArray();
• int c = 0;
• foreach (char ch in specialCh)
• {
• if (strpass.Contains(ch))
• {
• ++c;
• } }
• if (c == 0)
• {
• MessageBox.Show("*enter pass word atleast one
speciatl char ");
• textBox6.Focus();
• return false;
• }
Database Connectivity
• What is SQL Server in C#?
• SQL Server is a relational database management system
developed by Microsoft.
• There are different editions of Microsoft SQL Server.
• Microsoft SQL Server Express is a version of Microsoft’s
SQL Server relational database management system that is
free to download, distribute and use.
Use the following procedure.
• Step 1: Create a Windows Forms Form
• Open Visual Studio and create a new project and select
Windows Forms application and provide it the name “any
name".
• Step 2: Drag and drop a button.
• Now from the toolbox drag and drop a button and click on
the button.
Continued…
• Step 3: Database table
• Create a database table in SQL Server.
• Here the database name is “anyname" and “any name" is
the data.
• Step 4: Code for button click.
• First insert a namespace "using System.Data.SqlClient".
Install Sql Package If needed

• Install-Package System.Data.SqlClient -Version


4.8.3
DataBase Data Source
• It is a module of .Net Framework which is used to establish connection
between application and data sources.

• Data sources can be such as SQL Server and XML. ADO.NET


consists of classes that can be used to connect, retrieve, insert and
delete data.

• .NET Framework Data Providers


• It provides various objects such as Connection, Command,
DataReader and DataAdapter that are used to perform database
operations.
• The .NET Framework provides the following data providers
that we can use in our application.
NET Framework data
Description
provider
.NET Framework Data It provides data access for Microsoft SQL Server. It
Provider for SQL Server requires the System.Data.SqlClient namespace.

.NET Framework Data It is used to connect to data sources by using ODBC.


Provider for ODBC It requires the System.Data.Odbc namespace.

.NET Framework Data It is used for Oracle data sources. It uses the
Provider for Oracle System.Data.OracleClient namespace.
It provides data access for Entity Data Model
EntityClient Provider applications. It requires the
System.Data.EntityClient namespace.
.NET Framework Data It provides data access for Microsoft SQL Server
Provider for SQL Server Compact 4.0. It requires the
Compact 4.0. System.Data.SqlServerCe namespace.
continued
• The .NET Framework Data Provider for SQL Server
classes is located in the System.Data.SqlClient
namespace.
• using System.Data.SqlClient;
This namespace contains the following important classes.
Class Description
It is used to create SQL Server connection. This class
SqlConnection
cannot be inherited.

It is used to execute database queries. This class cannot


SqlCommand
be inherited.

It represents a set of data commands and a database


SqlDataAdapter connection that are used to fill the DataSet. This class
cannot be inherited.

It is used to read rows from a SQL Server database. This


SqlDataReader
class cannot be inherited.

This class is used to throw SQL exceptions. It throws an


SqlException exception when an error is occurred. This class cannot
be inherited.
SQL Server Connection
• To connect with SQL Server, we must have it installed in
our system.
• We are using Microsoft SQL Server Management Tool to
connect with the SQL Server.
• We can use this tool to handle database.
• Now, follow the following steps to connect with SQL
Server.
Continued…
1. Open Microsoft SQL Server Management Tool
• It will prompt for database connection. Provide the server
name and authentication.
2. Creating Database
3. Establish connection and create a table
• After creating database, now, let's create a table by using the
following C# code.
• In this source code, we are using created (student/student
info any valid name) database to connect.
Continued…
• Then select from Visual studio’s tool connect databases
server select sql server database and choose the database
name.
• From the database chosen you can create a table with
column and with their datatype and size.
• 4. Insert Data into the Table
• 5. Retrieve Record
• 6. Deleting Record
SqlConnection Class
• It is used to establish an open connection to the SQL Server
database.
• It is a sealed class so that cannot be inherited.
• SqlConnection class uses SqlDataAdapter and
SqlCommand classes together to increase performance
when connecting to a Microsoft SQL Server database.

Method Description
Open() It is used to open a database connection.

Close() It is used to close the connection to the database.


SqlCommand Class
• This class is used to store and execute SQL statement for
SQL Server database.
• SqlCommand() :-It is used to initialize a new instance of the
SqlCommand class.
• The ExecuteNonQuery() is one of the most frequently used
method in SqlCommand Object, and is used for executing
statements that do not return result sets (ie. statements like
insert data , update data ,delete ,search etc.) .
SqlDataAdapter Class
• The SqlDataAdapter works as a bridge between a DataSet
and a data source to retrieve data.
• SqlDataAdapter is a class that represents a set of SQL
commands and a database connection.
• It can be used to fill the DataSet and update the data
source.
Method Description

It is used to add rows in the DataSet to


Fill(DataSet)
match those in the data source.
DataTable
• DataTable represents relational data into tabular form.
• ADO.NET provides a DataTable class to create and use data
table independently.
• It can also be used with DataSet also. Initially, when we
create DataTable, it does not have table schema.
• We can create table schema by adding columns and
constraints to the table.
• After defining table schema, we can add rows to the table.
• We must include System.Data namespace before creating
DataTable.
Password Encryption
• Encryption is a means of securing digital data using one or more
mathematical techniques, along with a password or "key" used to
decrypt the information.
• The encryption process translates information using an
algorithm that makes
• Types of Encryption
• There are a range of different encryption methods in use
today,
• the most common being hashing, secret key encryption, and
envelope encryption the original information unreadable.
• Hashing
• A hashing algorithm takes an input value and transforms it
to a fixed-length output known as a “message digest”, “hash
value” or simply a “hash”.
• SHA-1 (Secure Hash Algorithm 1)is a cryptographic hash
function which takes an input and produces a 160-bit (20-
byte) hash value known as a message digest..
• SHA1 is more secure than MD5.
• The main difference between SHA1 and MD5 is that MD5
produce a 32 characters message digest, while SHA1
produce a 132 characters hexadecimal.
Example using SHA1 Password Encryption
.By create new class add this to encrypt
class Encryptpassword
{
public string pass(string data)
{
SHA1 sh = SHA1.Create();
byte[] hassdata = sh.ComputeHash(Encoding.Default.GetBytes(data));
StringBuilder stb = new StringBuilder();
for(int i = 0; i < hassdata.Length; i++)
{
stb.Append(hassdata[i].ToString());
}
return stb.ToString();
} }

You might also like