C# Unit - IV
C# Unit - IV
UNIT IV
2 Marks
1. What is Toolbox ?
5. What is a TextBox ?
TextBox is a graphical control element that allows the user to enter and edit
text. A TextBox control can be placed on a form, and its appearance and behavior canbe
customized using various properties, such as font size, and more. By default, a
TextBox control can accept single-line text input, but it can also be set to accept
multiline input.
6. What is a ComboBox ?
ComboBox is a graphical control element that provides a dropdown list of
items from which the user can select. It is commonly used to provide a list of options
for the user to choose from. The items in the dropdown list can be added at design
time or runtime, and can be populated from a database or other data source.
7. What is ListBox ?
1
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
ListBox is a graphical control element that displays a list of items to the user.
It allows the user to select one or more items from the list.. The items in the ListBox
can be added at design time or runtime, and can be populated from a database or other
data source.
ListBox ComboBox
The items are displayed in a scrollable The items are displayed in a dropdown
list for the user to select. menu.
ListBox can display multiple items at ComboBox can display only one item at
once. a time.
ListBox is suitable when the user needs omboBox is more suitable when the user
to select multiple items from a list. needs to select a single item from a list.
9. What is MenuStrip ?
MenuStrip is a graphical control element that provides a menu bar at the top of
a form. It allows the user to access various commands or features of the application.
The items in the MenuStrip are typically organized into menus and submenus, with
each item representing a command or feature of the application.
MenuStrip ToolStrip
MenuStrip is used to create menus with ToolStrip is used to create toolbars with
items . buttons and other controls.
MenuStrip is typically displayed at the ToolStrip is typically displayed below the
top of a form MenuStrip or in some other location on
the form.
MenuStrip usually contains text-based ToolStrip can contain a mix of text and
menu items image-based controls.
MenuStrip is often used to create the ToolStrip is often used to provide quick
main menu of an application access to frequently used commands or
tools.
2
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
3
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
form and associated with specific controls, such as buttons or textboxes, during design
time using the Properties window.
Pens
Brushes
Fonts
Transformations
5
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
6
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
5 Marks
• Windows Forms in Visual Studio has four important components that you'll interact with
as you create an app:
Solution Explorer
• All of your project files, code, forms, resources, will appear in this pane.
Properties
7
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
• This pane shows property settings you can configure based on the item selected.
• For example, if you select an item from Solution Explorer, you'll see property settings
related to the file.
• If you select an object in the Designer, you'll see settings for the control or form.
Form Designer
• This is the designer for the form. It's interactive and you can drag-and-drop objects from
the Toolbox. By selecting and moving items in the designer, you can visually compose the
user interface (UI) for your app.
Toolbox
• The toolbox contains all of the controls you can add to a form. To add a control to the
current form, double-click a control or drag-and-drop the control.
• Button
• Listbox
• Textbox
• If you double click the control it will be added into your form.
• You can position and size the controls according to your requirement
• click on each control and configure the settings in the Properties pane.
• You can also click on the form title area to select the form
8
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
• Text property of Label, Form and Button are changed. Also name property of listbox is
changed to Name.
• You should have a form in the designer that looks similar to the following:
Handle events
• Now that the form has all of its controls laid out, you need to handle the events of the
controls to respond to user input. With the form designer still open, perform the following
steps:
{
}
Add the following code
private void button1_Click(object sender, EventArgs e) {
if (!string.IsNullOrWhiteSpace(textBox1.Text) && !lstNames.Items.Contains(textBox1.Text))
lstNames.Items.Add(textBox1.Text);
}
• Run the app. (press F5 or Debug -> start without debugging) Enter some name in textbox
and click the button. The name will be added in the text box
9
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Displaying Messagebox
• Design a form with a button.
• Add the following code to its click event.
• If you run this app it will show this button, click it and it will show a dialog box.
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("welcome","Title",MessageBoxButtons.YesNo,Mess ageBoxIcon.Error);
}
• To open Toolbox, choose View > Toolbox from the menu bar, or press Ctrl+Alt+X.
Controls
• Button Allows the user to run a separate subroutine.
10
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
11
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
• TreeView Allows you to display a hierarchy of nodes with parents and child. • VScrollBar
Allows the user to drag a button in order to select a value. • WebBrowser Allows the user to
include a web browser on a form
Often used controls are
• Button
– Text property, -> Displays as caption
– Click Event
• Checkbox
– Text property -> Text displayed with Checkbox
– Checked property -> to select or deselect this property will be used. At runtime
– (CheckBox1.Checked) returns true when it is selected.
• RadioButton
– Text property -> Text displayed with Checkbox
– Checked property -> to select or deselect this property will be used. At runtime
– (radioButton1.Checked) returns true when it is selected.
• Combobox
• Text Property -> Value in the control. At design time for new line press enter to accept
press ctrl+enter.
12
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
{
textBox1.Text = "";
textBox2.Text = "";
checkBox1.Checked = false;
checkBox2.Checked = false;
checkBox3.Checked = false;
checkBox4.Checked = false;
radioButton1.Checked = false;
radioButton2.Checked = false;
comboBox1.Text = "CSE";
}
private void button1_Click(object sender, EventArgs e)
{
String name;
name = textBox1.Text;
MessageBox.Show("Hi " + name + " you have registered successfully");
}
13
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
14
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
The TableLayoutPanel control is a specialised panel that aids in the design and layout of the
ui. The Tablelayout Panel is essentially a table that provides cells for the individual hosting of
controls. Like other panels, it is a scrollable container that provides scroll bars when the
AutoScroll property is set to True.
15
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
The most important property of the TabControl is the TabPages property. TabPage controls
are specialized container controls that are hosted only inside TabControl controls. Each
TabPage has its own set of properties, and you can access these properties by editing the
TabPages property at design time. This launches the TabPage Collection Editor, as shown in
the following Figure:
16
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Individual TabPage controls are a lot like Panel controls. They are scrollable controls and will
generate scroll bars as needed if the AutoScroll property is set to True. Individual TabPage
controls also have a Text property, which represents the text shown in the tab that
represents this page in the TabControl. Also, like Panel controls,
TabPages have a BorderStyle property that can be set to None, FixedSingle, or Fixed3D, with
results similar to those in the Panel control.
The TabControl has several properties that you can use to customize the look and feel of the
control. The Appearance property controls how the tabs look. This property can be set to
Normal, Buttons, or FlatButtons, each of which generates a different visual style. The
Alignment property determines whether the tabs appear on the Top, Bottom, Left, or Right
of the TabControl. The TabControl also has a property called Multiline, which indicates if
more than one row of tabs is allowed. When it is set to True, multiple rows of tabs are
supported. When it is set to False, only a single row of tabs is allowed. Important properties
of the TabControl control and TabPage control are shown in Table 2-4 and Table 2-5,
respectively.
Important properties of TabControl control
17
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
• After drag the Menustrip on your form you can directly create the menu items by
type a value into the "Type Here" box on the menubar part of your form.
• From the following picture you can understand how to create each menu items on
mainmenu Object.
18
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
• If you need a seperator bar, right click on your menu then go to insert->Seperator.
• After creating the Menu on the form, you have to double click on each menu item
and write the programs there depending on your requirements.
• The following C# program shows how to show a messagebox when clicking a Menu
item.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1() {
InitializeComponent();
}
private void menu1ToolStripMenuItem_Click(object sender, EventArgs e) {
}
}
}
19
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
• To create a ToolStrip control at design-time, simply drag and drop a ToolStrip control
from Toolbox onto a Form.
• A ToolStrip control is nothing but a container without adding its child controls.
• A ToolStrip control is capable of hosting Button, Label, SplitButton, DropDownButton,
Separator, ComboBox, TextBox and ProgressBar controls.
• Add controls to ToolStrip control.
• If you click on a little dropdown handle on a ToolStrip control in designer, you will see
a list of possible controls that can be added to a ToolStrip.
20
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
• To add a control, simply select that control and it will be added to the ToolStrip
control.
• Another way to add controls to a ToolStrip control is by using the Items property.
• Click on the Items property and you will see Item Collection Editor
• We can add a Button, a TextBox, and a Label control to ToolStrip with a few
separators.
• Once these controls are added to a ToolStrip control, they all act as individual
controls and you can access them by using their Name property anywhere in the
code.
• Add three Button controls, three separators and a Label control.
• we are going to set an icon for the Button controls by setting Image property of
Button.
• Once you click on the browse option to browse an image, Resource editor window
pops up where you can import an image. Click on Import button and browse an
image file.
21
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
• Next step is to set the button click event handler. It is easy. Just double click or use
Events window and set click event handlers for all three buttons.
• private void toolStripButton1_Click_1(object sender, EventArgs e) {
10. How to add ToolTip control at design time and run time? (May-22)
Tool Tip control
• It represents a tiny pop-up box which appears when you place your pointer or cursor
on the control
• The purpose of this control is it provides a brief description about the control present
in the windows form.
• In ToolTip, you can check the ToolTip is active or not by using Active Property.
Add tooltip at design time
22
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
• Then drag and drop a label control and we will find the tooltip property
• Write something and then run the application
This will display a balloon tooptip on the label2 whose content is set dynamically.
23
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
24
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
10 marks
The Toolbox window displays controls that you can add to Visual Studio projects. To
open Toolbox, choose View > Toolbox from the menu bar, or press Ctrl+Alt+X.
You can drag and drop different controls onto the surface of the designer you are using, and resize and
position the controls. Toolbox appears in conjunction with designer views, such as the designer view of
a XAML file or a Windows Forms App project. Toolbox displays only those controls that can be used
in the current designer. You can search within Toolbox to further filter the items that appear.
The .NET version that your project targets also affects the set of controls visible in Toolbox. You can
change the target framework version from the project's property pages, if necessary. Select the project
node in Solution Explorer, and then on the menu bar, choose Project > projectname Properties. On
the Application tab, use the Target framework drop-down.
25
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
By default, Toolbox is collapsed along the left side of the Visual Studio IDE and appears when the
cursor is moved over it. You can pin Toolbox (by clicking the Pin icon on its toolbar) so that it remains
open when you move the cursor. You can also undock the Toolbox window and drag it anywhere on
your screen. You can dock, undock, and hide Toolbox by right-clicking its toolbar and selecting one of
the options.
If the Toolbox no longer appears as collapsed along the left side of the Visual Studio IDE, you can
add it back by choosing Window > Reset Window Layout from the menu bar.
You can rearrange the items in a Toolbox tab or add custom tabs and items by using the following
commands on the right-click context menu:
Rename Item - Renames the selected item.
List View - Shows the controls in a vertical list. If unchecked, the controls appear horizontally.
Show All - Shows all possible controls (not just the ones that apply to the current designer).
Choose Items - Opens the Choose Toolbox Items dialog box so that you can specify the items that
appear in the Toolbox. You can show or hide an item by selecting or clearing its check box.
Sort Items Alphabetically - Sorts the items by name.
Reset Toolbar - Restores the default Toolbox settings and items.
Add Tab - Adds a new Toolbox tab.
Move Up - Moves the selected item up.
Move Down - Moves the selected item down.
You can create custom Toolbox controls, starting either with a project template that's based
on Windows Presentation Foundation or on Windows Forms. You can then distribute your custom control
to your teammates, or publish it on the web by using the Toolbox Controls Installer
Components Tab :
26
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
DirectoryEntry - Creates a DirectoryEntry component instance that encapsulates a node or object in
the Active Directory hierarchy and can be used to interact with Active Directory service providers.
DirectorySearcher - Creates a DirectorySearcher component instance that you can use to perform
queries against the Active Directory.
ErrorProvider - Creates a ErrorProvider component instance, which indicates to the end user that a
control on a form has an error associated with it. For more information, see ErrorProvider component.
EventLog - Creates an EventLog component instance you can use to interact with system and custom
event logs, including writing events to a log and reading log data.
FileSystemWatcher - Creates a FileSystemWatcher component instance that you can use to monitor
for changes to any directory or file to which you have access.
HelpProvider - Creates a HelpProvider component instance that provides pop-up or online help for
controls.
ImageList - Creates a ImageList component instance that provides methods to manage a collection
of Image objects.
MessageQueue - Creates a MessageQueue component instance that you can use to interact with
message queues, including reading messages from and writing messages to queues, processing
transactions, and performing queue administration tasks.
Data tab :
DataGridView Provides a powerful and flexible way to display data in a tabular
format.
Displays data objects you can add to a forms and components. The Data tab of the Toolbox appears
when you create a project that has an associated designer. The Toolbox appears by default in the Visual
Studio integrated development environment; if you need to display the Toolbox, select Toolbox from
the View menu.
Name Description
DataSet Adds an instance of a typed or untyped dataset to the form or
component. When you drag this object onto a designer, it displays
a dialog box that allows you to select an existing typed dataset
class or specify that you want to create a new, blank, untyped
dataset. Note: You do not use the DataSet object on
the Toolbox to create a new typed dataset schema and class. For
more information, see Create and configure datasets.
A ContainerControl represents a control that can function as a container for other controls and
provides focus management. Controls that inherit from this class can track the active control they contain,
even when the focus moves somewhere within a different container.
ContainerControl objects provide a logical boundary for contained controls. The container control
can capture the TAB key press and move focus to the next control in the collection.
The container control does not receive focus; the focus is always set to the first child control in the
collection of contained controls. You do not typically inherit directly from
the ContainerControl class. Form, UserControl, and UpDownBase classes inherit from ContainerControl.
Provides focus-management functionality for controls that can function as a container for other
controls.
public class ContainerControl : System.Windows.Forms.ScrollableControl,
System.Windows.Forms.IContainerControl
ContainerClass Constructor :
For example , The following code example inherits from the ScrollableControl class and
implements the IContainerControl interface. Implementation is added to the ActiveControl property and
the ActivateControl method.
using System;
using System.Windows.Forms;
using System.Drawing;
set
{
// Make sure the control is a member of the ControlCollection.
if(this.Controls.Contains(value))
{
activeControl = value;
}
}
}
this.ScrollControlIntoView(active);
this.activeControl = active;
return true;
}
return false;
}
}
Properties :
[System.ComponentModel.Browsable(false)]
public System.Windows.Forms.Control? ActiveControl { get; set; }
2. AutoScaleDimensions - Gets or sets the dimensions that the control was designed to.
[System.ComponentModel.Browsable(false)]
public System.Drawing.SizeF AutoScaleDimensions { get; set; }
Property value - SizeF (A SizeF containing the dots per inch (DPI) or Font size that the control was
designed to.)
Exceptions - ArgumentOutOfRangeException
The AutoScaleDimensions property represents the DPI or font setting of the screen that the control was
29
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
scaled to or designed for. Specifically, at design time this property will be set by the Windows Forms
designer to the value your monitor is currently using. Then, when the form loads at run time, if
the CurrentAutoScaleDimensions property is different from the AutoScaleDimensions,
the PerformAutoScale method will be called to perform scaling of the control and all of its children.
Afterwards, AutoScaleDimensions will be updated to reflect the new scaling size.
3. AutoValidate - Gets or sets a value that indicates whether controls in this container will be
automatically validated when
the focus changes.
[System.ComponentModel.Browsable(false)]
public virtual System.Windows.Forms.AutoValidate AutoValidate { get; set; }
Property value - AutoValidate ( An AutoValidate enumerated value that indicates whether contained
controls are implicitly validated on focus change. The default is Inherit.)
Exception - InvalidEnumArgumentException
[System.ComponentModel.Browsable(false)]
public System.Windows.Forms.AutoScaleMode AutoScaleMode { get; set; }
Property value - AutoScaleMode ( An AutoScaleMode that represents the current scaling mode. The
default is None.)
Exception - InvalidEnumArgumentException
An AutoScaleMode value that is not valid was used to set this property.
The AutoScaleMode property specifies the current automatic scaling mode of this control. Scaling
by Font is useful if you want to have a control or form stretch or shrink according to the size of the fonts
in the operating system, and should be used when the absolute size of the control or form does not matter.
Scaling by Dpi is useful when you want to size a control or form relative to the screen. For example, you
may want to use dots per inch (DPI) scaling on a control displaying a chart or other graphic so that it
always occupies a certain percentage of the screen.
Methods :
30
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
An EventArgs that contains the event data.
Changing the font used by a ContainerControl will cause the layout to be recalculated and reapplied to the
contained controls if the AutoScaleMode property has a value of Font. Raising an event invokes the event
handler through a delegate.The OnFontChanged method also allows derived classes to handle the event
without attaching a delegate. This is the preferred technique for handling the event in a derived class.
The OnAutoValidateChanged method also allows derived classes to handle the event without attaching a
delegate. This is the preferred technique for handling the event in a derived class.
When overriding OnAutoValidateChanged(EventArgs) in a derived class, be sure to call the base
class' OnAutoValidateChanged(EventArgs) method so that registered delegates receive the event.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace CalculatorApp {
public partial class Form1 : Form {
double FirstNumber;
string Operation;
public Form1() {
InitializeComponent();
}
31
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
private void n3_Click(object sender, EventArgs e) {
if (textBox1.Text == "0" && textBox1.Text != null) {
textBox1.Text = "3";
} else {
textBox1.Text = textBox1.Text + "3";
}}
private void n4_Click(object sender, EventArgs e) {
if (textBox1.Text == "0" && textBox1.Text != null) {
textBox1.Text = "4";
} else {
textBox1.Text = textBox1.Text + "4";
}}
private void n9_Click(object sender, EventArgs e) {
if (textBox1.Text == "" && textBox1.Text != null) {
textBox1.Text = "9";
} else {
textBox1.Text = textBox1.Text + "9";
}}
private void n0_Click(object sender, EventArgs e) {
textBox1.Text = textBox1.Text + "0";
}
private void bad_Click(object sender, EventArgs e) {
FirstNumber = Convert.ToDouble(textBox1.Text);
textBox1.Text = "0"; Operation = "+";
}
private void bsub_Click(object sender, EventArgs e) {
FirstNumber = Convert.ToDouble(textBox1.Text);
textBox1.Text = "0"; Operation = "-";
}
private void bmul_Click(object sender, EventArgs e) {
FirstNumber = Convert.ToDouble(textBox1.Text);
textBox1.Text = "0"; Operation = "*";
}
GDI+ is a library that provides an interface that allows programmers to write Windows and Web
graphics applications that interact with graphical devices such as printers, monitors, or files.
All graphical user interface (GUI) applications interact with a hardware device (a monitor, printer, or
scanner), that can represent the data in a human-readable form. However, there is no direct
communication between a program and a device; otherwise, you would have to write user.
Microsoft’s managed GDI+ documentation divides its functionality into three categories: 2D vector
graphics, imaging, and typography:
1. 2D vector graphics
2. Imaging
3. Typography
4. Printing
5. Design
In the .NET Framework library, six namespaces define managed GDI+: System.Drawing,
System.Drawing.Design, System.Drawing.Drawing2D, System.Drawing.Imag ing,
System.Drawing.Printing, and System.Drawing.Text.
Figure 1.3 shows these namespaces. To use any of the classes defined in these namespaces, you must
include them in your application.
33
U20CSCM02 – C# and.Net Programming
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Graphics g=this.CreateGraphics();
Creating Pen
Used to draw shapes
Creating Brush
Used to display text
using System;
using System.Windows.Forms;
using System.Drawing;
34
U20CSCM02 – C# and.Net Programming