Vous êtes sur la page 1sur 22

20.07.

2010
GUI Programming using C#
-

Every GUI Application must have at least one Window Form


A window form is a class inherited from System.Windows.UI.Form class
This form works like a container for other controls
o Button
o TextBox
o Label
o Checkbox
o ListBox
o Combo box
o MenuStrip
o ToolStip
o StatusStrip
o ProgressBar
o Etc.
Each control has a fixed set of
o Properties
o Methods
o Events
Properties deal with values that can be of two types
o Design Time Property (F4)
o Run Time Property
Design time Properties are provided under Property Window that can be used
without any programming code
Run time properties get used though programming in Code Window which are
based on certain event
An event is some action taken by user or system like
o Click
o DoubleClick
o MouseMove
o KeyUp
o KeyPress
o KeyDown
o Tick
o Load
o UnLoad
o Etc.
Every control has its default event
o Form Load
o Button Click
o Etc.

Creating a new Project

File New Project Windows Form Application

Form control
- A container for Windows Applications
o Text
o Icon
o BackgroundImage
o BackgrounImageLayout
o StartPosition
o WindowState
o Opacity
o MinimizeBox
o MaximizeBox
o FormBorderStyle
o HelpButton
o ControlBox
o ShowInTaskBar
o TopMost
Common Properties on Controls
1. Name
a. Every control must have unique name
2. BackColor
3. ForeColor
4. Font
5. Size
6. Location
7. Enabled=true/false
8. Visible=true/false
9. TabIndex
10. TabStop
11. Dock
Naming a control
- If possible use Hungarian notation given by Charles Simony of Hungary. It states
that use three character prefix to define type of control along with purpose of
control
o Form frm
o Label lbl
o TextBox txt
o Button btn or cmd
o Combo Box cbo
o ListBox lst
o Checkbox chk
o Etc.

Label control
- To provide some text
o Text
- Use & to make the hot key
TextBox control
- To create single line text, multi line text and password field
o Text
o PasswordChar
o Multiline
o Scrollbars
o MaxLength
o ReadOnly
o TextAlign
Button control
-

To create a push buttons


o Text
o Image
o TextAlign
o ImageAlign
o FlatStyle
o FlatAppearance
Use & for hot key

ToolTip control
-

Used to provide a tooltip on different controls


It add a ToolTip Text property on every control
o IsBalloon
o ToolTipIcon
o ToolTipTitle

Adding a new window form


Project Add Windows Form
Making a form as startup form
-

Select Solution Explorer


o Select Program.cs file
o Create an object of the form for which you want as first form

Test Application 1
Write a Windows Application to input a string and show its reverse.

private void cmdReverse_Click(object sender, EventArgs e)


{
string s = txtString.Text;
StringBuilder sb = new StringBuilder();
for (int i = s.Length - 1; i >= 0; i--)
sb.Append(s[i]);
txtReverse.Text = sb.ToString();
}

Test Application 2

Write an application to get a number and Print some of its digits


private void cmdSum_Click(object sender, EventArgs e)
{
int num = int.Parse(txtNumber.Text);
int sum = 0,d;
while (num > 0)
{
d = num % 10;
sum += d;
num /= 10;
}
txtResult.Text = sum.ToString();
}
Assignment

Write a program to have an array of 10 numbers. Input the data from a text box and pass
into an array element.
On a label show current number of inputs. If inputs goes 10 print the smallest and biggest
of those numbers on the form.
22.07.2010
Checkbox control
- To select none or all
o Text
o Image
o TextAlign
o ImageAlign
o Checked
Test Case
Create a form having a checkbox [ ] Agree to Terms and Condition and a button having
text and image for Next
When checkbox is checked Enable the button otherwise disable the button

Example
private void chkAgree_CheckedChanged(object sender, EventArgs e)
{
cmdNext.Enabled = chkAgree.Checked;
}

Radio Button control


- To select only one item from Group
o Text
o Image
o TextAlign
o ImageAlign
o Checked
- To group the controls select containers
o GroupBox
o Panel
Test Case
Create two groups
Gender Male, Female
Qualification MBA, MCA
DateTimePicker control
- To select Date, Time or Both
o Format
o CustomFormat
d Date
M Month
Y year
h hours
m minutes
s seconds
o ShowUpDown
o Value
Example
this.Text = dateTimePicker1.Value.ToString("dd-MMM-yyyy");

Working with Dialogs


.NET Provides different kind of dialogs. Use MessageBox class with Show() method to
show a dialog. Dialogs can be of two types
1. Simple Message Dialogs
MessageBox.Show(string message, string title, MessageBoxButtons b, MessageBoxIcon ic)

2. Response Dialogs

DialogResult MessageBox.Show(string message, string title, MessageBoxButtons b,


MessageBoxIcon ic)

Example
Write a program to ask as user for being adult. If yes, allow to join else send back
Solution

private void button2_Click(object sender, EventArgs e)


{
DialogResult ans = MessageBox.Show("Are you adult", "Query",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (ans == DialogResult.Yes)
MessageBox.Show("You can join us", "Welcome",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
else
MessageBox.Show("Sorry! Not Allowed", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Stop);
}

Working with Dialog Controls


.NET Provide five dialog controls under Dialogs section
-

FontDialog
ColorDialog
OpenFileDialog
SaveFileDialog
FolderBrowserDialog

All such controls provides ShowDialog() method


Color Dialog
- To select a color
o Color
o FullOpen=true/false

Sample Code
private void cmdColor_Click(object sender, EventArgs e)
{
colorDialog1.FullOpen = true;
colorDialog1.ShowDialog();
textBox1.ForeColor = colorDialog1.Color;
}

Font Dialog
- To select a font and some colors
o Font
o Color
o ShowColor=true/false
RichTextBox control
- Advance version of TextBox that allows to work with selected portion of text
o Text
o ForeColor
o BackColor
o SelectionColor
o SelectionFont
o Cut()
o Copy()
o Paste()
o SelectAll()
o LoadFile()
o SaveFile()
PictureBox control
- To select an image
o Image
o SizeMode
o BorderStyle
Open File Dialog/Save File Dialog control
- Allows to select a file
o Filter
o FileName
Example
private void cmdBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.FileName = "";
openFileDialog1.Filter = "Image Files|
*.jpg;*.gif;*.png;*.bmp";
DialogResult ans=openFileDialog1.ShowDialog();
if (ans == DialogResult.OK)
{
pictureBox1.Image =
Image.FromFile(openFileDialog1.FileName);
}

FolderBrowser Dialog
- Used to select a folder
o SelectedPath
Creating Menus
-

Menus can be of two types


o Menu Strip
o Context Menu Strip
Each Menu contains
o Image
o Shortcut Key
o ToolTipText
o Text
Menus are provided under Menus and Toolbars section

Context Menu is applied to certain control with ContextMenuStrip property


26.07.2010
Note: To work with current date and time use DateTime class with Now property
Creating a toolbar
- Use ToolStip control
- Add the controls like Button, Combo box etc.
- Add Image and ToolTip on the buttons
- Now write the code on button
Creating Status Bar
-

Use StatusStrip control


Use Items collection to divide the status strip into section
Set AutoSize as property as false

Timer control
- to repeat a process after given interval of time
o Interval=time in milliseconds
o Enabled=true/false
- Provided under Components section
Creating MDI Application
- Allows to create/open Multiple Documents under one Window
- Each of such application must have a MDI Container
- An application can have many normal forms but only one MDI Container
- To make a form as MDI Form set its

o IsMdiContainer =true/false
To set a form as child form use MdiParent property
To set the placement of child forms use LayoutMdi() method with MdiLayout
enumerator
To get reference current form use ActiveMdiChild property
To get reference of all the children inside an MDI form use MdiChildren
collection
To get reference of a control inside a form use Controls collection

Example
colorDialog1.ShowDialog();
RichTextBox t = (RichTextBox) ActiveMdiChild.Controls["txtMain"];
t.SelectionColor = colorDialog1.Color;

Linking the forms


-

On click on a button or menu item make an object of other form


Hide the first form
Call ShowDialog() method to show the form
Dispose the current one and unhide first one

Working with Event Method Argument object sender


- Provides information about the current control on which some activity is done
Example

private void ChangeColor(object sender, EventArgs e)


{
Label x = (Label)sender;
f.BackColor = x.BackColor;
}

27.07.2010
Creating Web Browser
-

Use WebBrowser control

Understanding the methods arguments sender and e


-

Case 1

sender gives reference the current control on which activity has done
e helps in getting information and taking certain instructions from us

Show the current mouse position on a form when we move the mouse pointer on it.
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
string x = "Mouse is on " + e.X + "," + e.Y;
this.Text = x;
}

Case 2
Write an application to ask a dialog when we close a form by clicking on X
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult ans = MessageBox.Show("Quit the application", "Quit",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (ans == DialogResult.No)
e.Cancel = true;
}

Case 3
Create a text box to input a mobile number. Allow to input only digits and backspace.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int num =(int) e.KeyChar;
//this.Text = num.ToString();
if (!((num >= 48 && num <= 57) || num == 8))
e.Handled = true;
}

Case 4
Create a textbox to type a URL. If Enter key is pressed then show that URL in a web
browser. If Ctrl+Enter key is pressed then join http protocol and .com extension
private void textBox2_KeyUp(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.Enter)
{
string s = "http://" + textBox2.Text + ".com";
textBox2.Text = s;
webBrowser1.Navigate(s);
}
else if (e.KeyCode == Keys.Enter)
{
webBrowser1.Navigate(textBox2.Text);
}
}

Case 5
Refresh the browser when F5 key is pressed
Note: Write the such codes on the Form. Set KeyPreview
property of the form as true.

private void Form1_KeyUp(object sender, KeyEventArgs e)


{
webBrowser1.Refresh();
}

Using Tabcontrol
- used to hold more controls in less space
- Provided under Containers section
- It contains TabPages collection
Setting Icon of a Project
-

Project Properties Icon

Creating Setup of a Project


-

Change the mode from Debug to Release


Select the target CPU
o Project Properties Build Platform Type
Assign the information about the software product
o Company Name
o Version
o Trademark
o Etc
o Project Properties Application Assembly Information

Add a new project in same solution


File Add New Project Other Project Types Setup and Deployement
Setup Project
Select Application Folder properties Add Project Output Ok
Add the Icon and other files.
Create the shortcut of application file and drop into Desktop and Program Menu folders
Rename the shortcuts and assign the Icon
Select the Setup Project from Solution Explorer and then select its properties
Select Pre-requisites
Build the Project

29.07.2010
ADO.NET (ActiveX Data Objects for .NET)
-

A set of classes under .NET Framework for database operations


All related class are placed under some libraries
o System.Data.dll
o System.Data.OracleClient.dll
Such libraries provide some namespaces called as Providers
o System.Data
o System.Data.Odbc
o System.Data.OleDb
o System.Data.OracleClient
o System.Data.SqlClient
System.Data provides commonly used classes used by any database including
XML
o DataTable, DataSet, DataRow, DataColumn, DataRelation etc.
System.Data.Odbc provides classes that used Open Database Connectivity
(ODBC) Manager of MS Windows. It allows to use any kind of database. It
required a Data Source Name (DSN).
o OdbcConnection
o OdbcCommand
o OdbcDataReader
o OdbcDataAdapter
o OdbcParameter
System.Data.OleDb provides classes that can directly use any database without
any DSN but needs driver or provider.
o OleDbConnection
o OleDbCommand
o OleDbDataReader
o OleDbDataAdapter
o OleDbParameter
System.Data.SqlClient provides classes that works with SQL Server only
o SqlConnection
o SqlCommand
o SqlDataReader
o SqlDataAdapter
o SqlParameter
System.Data.OracleClient provides classes that works with Oracle only
o OracleConnection
o OracleCommand
o OracleDataReader
o OracleDataAdapter
o OracleParameter

Main database used are


1. MS Access

2. Sql Server
3. Oracle
Using MS Access as Database
-

Create a database
o 2003 (.mdb)
o 2007 & 2010 (.accdb)
o Example
B25db.mdb
Now create your tables as per your project
o Relations table
rcode AutoNumber Auto Generated - PK
rname Text 20
o Members table
mcode AutoNumber Auto Generated PK
mname Text 50
email Text 50
mobile Text 10
bloodgroup Text -3
rcode Number FK

Setting relationship among the tables as Primary and Foreign key in MS Access
Select Tools Relationship
Add both the tables and Drag and drop the field for setting the relationship as one-tomany relationship
Create the Forms as front-end
1. Relations Master
2. Member Master

Create a DSN for your database


Control Panel Admin Tools ODBC System DSN Add Select the driver
as

Microsoft Access Driver (*.mdb) 2003


Microsoft Access Driver (*.mdb, *.accdb) 2007 & 2010
Now provide the DSN name and select your database
e.g. b20access
Now write the program code on Save button
Step 1
Import the namespace System.Data.Odbc
Create a connection object using the information we have and open the connection
OdbcConnection cn=new OdbcConnection("dsn=b20access");
or
OdbcConnection cn=new OdbcConnection();
cn.ConnectionString="dsn=b20access";
cn.Open();
Step 2
Create the SQL Statement to be executed
string sql = "INSERT INTO relations(rname) VALUES('" +
txtRelation.Text + "')";

Step 3
Create an object of OdbcCommand and execute the SQL
statement using ExecuteNonQuery() method

Setting a button as Default button when Enter key


is pressed
-

Define AcceptButton property on a from

30.07.2010
Using MS Access with OleDb Technology
-

Do not require any DSN


It need the driver name who can connect with database

Visual Studio provides a tool


o Tools Connect to Database
Create the connection string and use it

Import System.Data.OleDb
Create the SQL Statement. Use String.Format() method to create the SQL statement
Example

OleDbConnection cn = new OleDbConnection();


cn.ConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=F:\Batches2010\20\b20db.mdb";
cn.Open();
string sql = string.Format("INSERT INTO relations(rname)
VALUES('{0}')", txtRelation.Text);
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Saved");

Creating Dynamic Path for database file


-

Place your database file near to executable file of the project


Use Application.StartupPath property to get the folder name of executable file

OleDbConnection cn = new OleDbConnection();


cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source="+ Application.StartupPath + @"\b20db.mdb";
cn.Open();
string sql = string.Format("INSERT INTO relations(rname)
VALUES('{0}')", txtRelation.Text);
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Saved");

Passing parameters to SQL Statements


-

Use ? in place of data in SQL statements


Pass the data later on to OdbcCommand or OleDbCommand object using
AddWithValue() method

OleDbConnection cn = new OleDbConnection();


cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=" + Application.StartupPath + @"\b20db.mdb";
cn.Open();
string sql = "INSERT INTO relations(rname) VALUES(?)";
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.Parameters.AddWithValue("rname", txtRelation.Text);
cmd.ExecuteNonQuery();
cn.Close();

MessageBox.Show("Record Saved");

Creating class for database operations


-

Create a class and methods to return a connection on demand


Add a class file from
o Project Add Class

using System.Data.OleDb;
using System.Windows.Forms;
class Db
{
public static OleDbConnection GetConnection()
{
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=" + Application.StartupPath + @"\b20db.mdb";
cn.Open();
return cn;
}
}

Placing Information Outside the class under Application Configuration file


Add the App.Config file from
i. Project Add New Item Application Configuration File
Select <appSettings> section
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="provider" value="Microsoft.Jet.OLEDB.4.0"/>
<add key="dbname" value="b20db.mdb"/>
</appSettings>
</configuration>

using
using
using
class
{

To read this information in any class or Window Form


use ConfigurationSettings class of System.Configuration
namespace
System.Data.OleDb;
System.Windows.Forms;
System.Configuration;
Db

public static OleDbConnection GetConnection()


{
string provider =
ConfigurationSettings.AppSettings["provider"];
string dbname = ConfigurationSettings.AppSettings["dbname"];
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = "Provider="+ provider +";Data Source="
+ Application.StartupPath + @"\"+dbname;

cn.Open();
return cn;
}

02.08.2010
Working with SQL Server
-

Start the Server and not down the server name or IP Address
Create a database
o E.g. b20
Create your tables
o Product table
Pcode Primary Key - Identity
Pname
Price
Qty
o Setting the auto incremental
Select the field name as Pcode
Select it properties
Identity Specifications
o Is Identity =true
o

Information required to connection with database


Data Source=<server name or ip addres or . or (local)> e.g. BPSHARMA
Database=<database name> e.g. b20
User Id=<login> e.g. sa
Password=<password> e.g. pass
Integrated Security=true
To connect without login and password on local machine
Creating a connection string
Tools Connect to Database
Example
Data Source=.;Initial Catalog=b20;Integrated Security=True
Data Source=.;Initial Catalog=b20;User ID=sa; Password=pass
Provider : System.Data.SqlClient
Import the provider namespace

Making the parameters


- Use @ with the parameters name to make the parameters

Running SQL Statements using xxxCommand object


-

xxxCommand object provides three methods


o int ExecuteNonQuery()
All commands except SELECT
o xxxDataReader ExecuteReader()
When reading records with SELECT
o object ExecuteScaler()
To read single value from SELECT query

Example

private void cmdSave_Click(object sender, EventArgs e)


{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "Data Source=.;Initial
Catalog=b20;Integrated Security=True";
cn.Open();
string sql = "INSERT INTO product(pname,price,qty)
VALUES(@pname,@price,@qty)";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.Parameters.AddWithValue("@pname", txtPName.Text);
cmd.Parameters.AddWithValue("@price", txtPrice.Text);
cmd.Parameters.AddWithValue("@qty", txtQty.Text);
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Saved");
}

Using Oracle as database


-

Start the Oracle Server and Create your tables


o Employee Table
empid - Numeric
name - varchar
email varchar
Give the reference of System.Data.OracleClient.dll file
Use Provider as System.Data.OracleClient
Use : in place of @ to make the parameter

03.08.2010
Saving Images to Database
- Select an image to save into a PicureBox
- Read the Image from the PictureBox and place it into memory using a class
MemoryStream class of System.IO namespace
- Convert data into byte array using GetBuffer() method of MemoryStream class
- Save the byte array into database
- To pass binary data as parameter create an object of SqlParameter class
SqlParameter p=new SqlParameter(paramname, data type);
p.Value=binary data;

Now use Add() method in place of AddWithValue() method

Test Case
Create table as Student (rollno numeric, name varchar(50), photo Image)
Create front-end form
Example
private void button2_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "Data Source=.;Integrated
Security=true;Database=b20";
cn.Open();
string sql = "INSERT INTO student
VALUES(@rollno,@name,@photo)";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.Parameters.AddWithValue("@rollno", textBox1.Text);
cmd.Parameters.AddWithValue("@name", textBox2.Text);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] data = ms.GetBuffer();
ms.Close();
SqlParameter p = new SqlParameter("@photo",
SqlDbType.Image);
p.Value = data;
cmd.Parameters.Add(p);
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Saved");
textBox1.Clear();
textBox2.Clear();
pictureBox1.Image = null;
}

Creating and Using Stored Procedures


-

To create a stored procedures


o Select your database
o Select Programmability
o Select Stored Procedure
o Select New Stored Procedure

CREATE PROCEDURE SaveStudent


@rollno int,
@name varchar(50),
@photo Image
AS
BEGIN
INSERT INTO student VALUES(@rollno, @name,@photo);
END
GO

Select it and press F5 to execute it


To run a stored procedure use two properties
1. CommandText="procedure name";
2. CommandType=CommandType.StoredProcedure;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SaveStudent";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cn;
Reading data from Database
-

Data can be read using two methods


o Connected Mode
o Disconnected Mode
In connected mode data is available to access till the connection is open. We can read
only one record at a time in forward direction.
In disconnected mode, we can read the records from server to the client, hold them in
memory event after closing the connection. All records are available at one go. We can
see any records at any time

Using Connected Mode


- Create the SELECT command and pass the result to SqlDataReader
- Methods of SqlDataReader
o bool Read()
Moves the record pointer until end of records reached
o To read data we can pass the column index number or column name
09.08.2010

Reading data in disconnected mode


-

To read data from data database and hold it at the client even after closing the
connection is called as disconnected mode
Use container classes to hold the data
o DataTable
DataTable()
DataTable(string tablename)
o DataSet
DataTable class can hold result of single query
DataSet is a collection of DataTable type objects and can hold result of many
queries that can be accessed using Tables collection of DataSet
To read data from database and hold it into some container use xxxDataAdapter
class
It provides Fill() method to fill data into a container

Example
string sql="Select * from employee";

SqlDataAdapter da=new SqlDataAdapter(sql,cn);


DataTable dt=new DataTable();
da.Fill(dt);
cn.Close();
-

Each DataTable provides two collections


o Rows collection
o Columns collection

Example
Write a program to read the records from Student table and show them one by one. Create
buttons First, Last, Prev and Next to show those records.
Also show the current record position and total number of records.
Data Binding
-

To bind some data source to a control using DataSource property


To show all records in Grid format use DataGridView control
To bind data with some combo box use some more property
o DisplayMember="fieldname"
o ValueMember="fieldname"

Relations *
rcode
rname

Members *
mcode
mname
mobile
email
rcode

10.08.2010
DataView control
-

To resort and re-filter data available in a DataTable


o DataView(DataTable dt)
Define RowFilter property to define the condition

o RowFilter="condition";
To sort the records based on a field use Sort property
o Sort="fieldname";
Doctors *
dcode
dname
mobile
email

Prescriptions *
pcode
mcode
dcode
dop
symptoms
spinstructions

Members *
mcode
mname
mobile
email

Medicines *
medcode

rcode

medname
medtypecode
dosage
pcode

Relations
rcode
rname

MedicineTypes *
medtypecode
medtypename

Crystal Reports
-

A reporting tool from Seagate that provides advance reports that can be printed or
exported
Add a crystal report from
o Project Add New Item Crystal Report
A file get created as .rpt
Select the table name and field names to be added on report then style of report
To use this report
o Add a new blank form
o Add the CrystalReporViewer control
o Select the CrystalReport name and its properties like
DisplayGroupTree=true/false
To show the report create an object of the form and show the report

Vous aimerez peut-être aussi