0% found this document useful (0 votes)
15 views

Lecture 08 - windowsform application

Uploaded by

anjalee himalki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Lecture 08 - windowsform application

Uploaded by

anjalee himalki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Windows Form Application II

Object oriented with visual programming


M. Y Abdur Rahman
Sample program
• private void btn_dw_Click(object sender, EventArgs e)
• {
• int x = 0;
• do
• {
• listBox1.Items.Add(x);
• x++;
• }
• while (x < 5);
• }

• private void btn_fl_Click(object sender, EventArgs e)


• {
• for(int i=1;i<=5;i++)
• {
• listBox1.Items.Add(i);
• }
• }
Advanced Controls
• Timer:
• The timer control is one of the few controls always hidden at run time.
• It can be placed even top of existing controls.
• The timer checks the system time and acts accordingly.
• Picture Box:
• It display icons or bit map or meta files.
• Acts as a visual container for the controls
• Important properties is Size Mode
❑Auto size
❑Centre image
❑Stretch image.
• Tool bar (Tool strip):
• This is used to display toolbar button controls.
• Which can be appear as standard button, a toggle style button or a drop down button.
• A user can assign images to the buttons as well.
• Panel and Group box:
• Group box is used as container for radio button and check box
• Group box always has border and title
• In group box we cannot display scrollbars
• Group box has the text property
• Panel does not have the text property
• We can display scroll bars in panel
• Title cannot be set for the panel
• In panel by using border style property we can display border.
• Menu(Menu strip):
• By using the main menu control the user can have standard windows menu at the top
of the form.
• Creation of pop-up menus is possible by using the context menu control.
• The menu bar appears below the title bar and it may contain one or more menu titles.
• When a menu title is clicked it displays a set of menu items.
• Menu notable properties:
• Checked: menu item has a check mark beside it if the property is true.
• Visible: Determines whether the menu item can be seen.
• Short cut: Set the short cut keys to access the item directly.
• Show short cut: Mark the visible of short cut keys.
• Date time Picker:
• Can use this control to select the date.
• Date time picker looks like a combo box and contains a date.
• Month calendar:
• This is also allow the user to select the date.
• The difference between the DateTimePicker and the month calendar is-
• In month calendar we select the date visually and
• In DateTimePicker when we want to make a selection we click on the drop down arrow and
select the date from the month calendar which is displayed.
• Status Bar:
• Status bars are used to display status messages at the bottom of the form.
• Used to provide additional information such as page numbers, display a message ect.
• A status bar control is a combination of status bar panel where each panel can be used
to display different information.
• Example: one panel can display current application status and other can display date and
other information and more.

• Tool tip:
• A tooltip is a small pop-up window that displays some information when you rollover
on a control.
• Tooltip class represents a tooltip control. Once a tooltip object is created, we need to
call set tooltips method and pass a control and text.
Program with tool bar and status bar

Button
Check box
Text box
Status strip – status label
Tool strip – button, label
• private void btn_enter_Click(object sender, EventArgs e)
• {
• toolStripLabel1.Text = "You clicked the Enter button";
• }

• private void toolStripButton1_Click(object sender, EventArgs e)


• {
• txt_name.Text = "This is the ToolStripButton";
• }
• private void chk_click_CheckedChanged(object sender, EventArgs e)
• {
• if(chk_click.Checked)
• {

• toolStripStatusLabel1.Text = "Check box is checked";


• }
• else
• {
• toolStripStatusLabel1.Text = "Check box is unchecked";
• }
• }
Program for tool tip
• public partial class Form1 : Form
• {
• public Form1()
• {
• InitializeComponent();
• }

• private void btn_click_Click(object sender, EventArgs e)


• {
• toolTip1.ShowAlways = true;
• toolTip1.SetToolTip(btn_click, "Click me to execute");
• }
• }

By setting 1sBalloon to true it makes the tooltip balloon that looks like below
Dialog Boxes
• These are used to display information and prompt the user for data needed
to continue with the application three types are there.
• Predefined Dialog Box: Message Box.
• Customer Dialog Box: Created with forms for customizing an existing dialog box.
• Standard Dialog box: File, Print, Font, Save, open and colour.
• Standard Dialog boxes
• Colour Dialog: This contains different colours, enabling the user to choose the colour.
• Font Dialog: Contains all font, style and size to change the font of particular text.
• Save file dialog: Used to save a file.
• Open a file dialog: Used to open files of different extension which is required.
• Print Dialog: Used to display the print settings and print to the file.
Sample program for standard boxes
• private void btn_open_Click(object sender, EventArgs e)
• {
• openFileDialog1.ShowDialog();
• pictureBox1.SizeMode= PictureBoxSizeMode.StretchImage;
• pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);

• }

• private void btn_save_Click(object sender, EventArgs e)


• {
• saveFileDialog1.Filter =
"Jpegimage|*.jpg|bitmapimage|*.bmpgifimage|*gif|*png|*Jpeg";
• saveFileDialog1.Title = "save image file";
• saveFileDialog1.ShowDialog();
• pictureBox1.Image.Save(saveFileDialog1.FileName,
System.Drawing.Imaging.ImageFormat.Jpeg);
• }
• private void btn_print_Click(object sender, EventArgs e)
• {
• printDialog1.ShowDialog();
• }

• private void btn_chcolor_Click(object sender, EventArgs e)


• {
• colorDialog1.ShowDialog();
• listBox1.ForeColor = colorDialog1.Color;
• }

• private void btn_chfont_Click(object sender, EventArgs e)


• {
• fontDialog1.ShowDialog();
• listBox1.Font = fontDialog1.Font;
• }
Menus & Timer
• private void exitToolStripMenuItem_Click(object sender, EventArgs e)
• {
• this.Close();
• }

• private void timer1_Tick(object sender, EventArgs e)


• {
• label1.Text = DateTime.Now.ToString();
• }
Exception Handling
• A problem that arises during the execution of a program.
• Can detect and handle program errors in your code.
• Eg:
✓Validating user input
✓Checking for null objects
✓Verifying the values returned from method from one part of a program to another.
• Exception provide a way to transfer control from one part of a program to
another.
C# exception handling is built upon four keywords

• try: identifies a block of code for which particular exceptions will be


activated. It’s followed by one or more catch blocks.
• catch: program catches an exception with an exception handler at the place
in a program where you want to handle the program. The catch keyword
indicates the catching of an exception.
• finally: used to execute a given set of statements, whether an exception is
thrown or not thrown,
• Eg: if you open a file, it must be closed whether an exception is raised or not.
• throw: throws an exception when a problem shows up. This is done using a
throw keyword.
• Can list down multiple catch statements to catch different type of exceptions.
Try{
//statement causing exception
}
Catch(Exception Name e1){
//error handling code
}
Catch(Exception Name e2){
//error handling code
}
Catch(Exception Name e n){
//error handling code
}
finally{
//statements to be executed
}
Important Exception
• Exception: This is the general exception class which handle any kind of
exceptions.
• IOExcetion: Handles I/O errors.
• IndexOutOfRangeException: Handles errors genered when a method refers
to an array index out of range.
• NullReferenceException: Handle errors generated from referencing a null
object.
• DivideByZeroException: Handles erros generated from dividing a dividend
with zero.
• InvalidCastException: Handles errors generated during typecasting.
• OutOfMemoryException: Handles errors generated from insufficient free
memory.
• FormatException: The format of an argument is wrong.
Sample program for handling format exception
• public partial class Form1 : Form
• {
• public Form1()
• {
• InitializeComponent();
• }
• double no1, no2;
• private void btn_add_Click(object sender, EventArgs e)
• {
• try
• {
• no1 = Convert.ToDouble(txt_no1.Text);
• no2 = Convert.ToDouble(txt_no2.Text);

• txt_ans.Text = (no1 + no2).ToString();


• }
• catch(FormatException)
• {
• MessageBox.Show("Please enter numeric
value","Error",MessageBoxButtons.OKCancel,MessageBoxIcon.Error);
• }
• }
• }
Sample program for handling out of memory exception
• public Form1()
• {
• InitializeComponent();
• }

• private void button1_Click(object sender, EventArgs e)


• {
• try
• {
• openFileDialog1.ShowDialog();
• pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
• pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
• }
• catch(OutOfMemoryException)
• {
• MessageBox.Show("Please select a picture file");
• }
• }
Exercise 1
• Write a simple program for handle.
DivideByZeroException. If user try to divide a value from “0” the handle this
exception. Also use final block for show the answer.
Input validation
Why we need validations?
• When users enter data into your application, you may want to verify that the
data is valid before your application uses it.
• You may require that certain text fields not be zero-length, that a field be
formatted as a telephone number or other type of well-formed data(Ex:
NIC, Email), or that a string not contain any unsafe characters that could be
used to compromise the security of a database.
• Windows forms provides several ways for you to validate input in your
application.
Input validations with masked Text Box
• If you need to require users to enter data in a well-defined format. Such as a
telephone number or a part number, you can accomplish this quickly and
with minimal code by using the Masked Text Box control.
• A mask is string made up of characters from a masking language that
specifies which characters can be entered at any given position in the
textbox.
• The control displays a set of prompts to the user. If the user types an
incorrect entry, for example, the user types a letter when a digit is required
the control will automatically reject the input.
Program with Masked Text Box

You can only give numbers as well as only 10 numbers


Validating using code

• Validate the text Box(for Telephone Number) that user must enter 10
numbers.
• private void maskedTextBox1_MaskInputRejected(object sender,
MaskInputRejectedEventArgs e)
• {
• if(maskedTextBox1.Text.Length != 10)
• {
• MessageBox.Show("Wrong telephone number, Please check
it again","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
• }
• }
Validations using codes
• Validate the textbox if empty and if number entered(only characters can
enter)

• if(string.IsNullOrEmpty(txt_name.Text)||
txt_name.Text.Any(Char.IsDigit))
• {
• MessageBox.Show("Please enter your first name");

• }
• if(string.IsNullOrEmpty(txt_name.Text)||
txt_name.Text.Any(c=>char.IsNumber(c)))
• {
• MessageBox.Show("Please enter your first name");
• }
Validating using error provider

• It is used to indicate error associated with the controls.


• The default icon for the Error Provider is a red cycle with an exclamation
point.
• IT allows us to set an error message for any control on the form when the
input is not valid.
Sample Program for error provider
• private void btn_login_Click(object sender, EventArgs e)
• {
• try
• {
• if(txt_un.Text.Length>0){
• error_un.Clear();

• if (txt_pass.Text.Length > 0){
• error_pass.Clear();
• }
• else{error_pass.SetError(txt_pass, "Password is required"); }

• }
• else{error_un.SetError(txt_un,"User name is required");}

• }
• catch(Exception ex)
• {
• MessageBox.Show(ex.ToString());
• }
• }

You might also like