cookieChoices = {};
Showing posts with label C Sharp. Show all posts
Showing posts with label C Sharp. Show all posts

Wednesday, 20 August 2014

Windows Forms

Windows Forms
Windows forms provide many enhancements over standard VB forms including:
Rich set of Controls: By using the classes in the System.Windows.Forms namespace, you can create windows applications that take full advantage of the rich user interface features available in Microsoft Windows Operating System. This namespace provides “Form” class and many other controls that can be added to the form to create user interface.
Advanced Printing Support: .net provides different controls and dialog boxes to handle printing options. Ex: PrintSetupDialog, PrintPreviewDialog, PrintPreviewControl etc.
Advanced Graphics Support: we can design 2D graphics with the use of namespaces like System.Drawing, System.Drawing.Drawing2D etc.
Visual Inheritance: windows forms are classes and can benefit from inheritance. Windows forms can be inherited from derived form that automatically inherits the controls and code defined by base forms.
Form:
          A form is the window that is used to present information to or accept information from the end use. The form can be a single window, and MDI window or a Dialog Box.
A form will have two windows. Designer and code
The Windows Forms Designer:
  • Contains comments in XML Documentation
  • A Container object is required if you need to group the objects together.
The advantage of this object is, even though there may be elements in the application that are not controls, the “Container” object allows us to group everything together.
Private System.ComponentModel.Container Components=NULL;
  • The Dispose() method is used to perform any operation that are necessary when garbage collection is done.
  • In the InitializeComponent() method, the controls are instantiated and are set to their initial behavior.
  • Then Main() method specifies the starting point of the application.
Form Properties:
Property
Description
AcceptButton
Specifies which buttons click event has to be executed when the user presses enter key
CancelButton
Specifies which buttons click event has to be executed when the user presses ‘Esc’ key
BackColor
Sets the forms back color
ControlBox
True/false to display min,max,close controls
FormBorderStyle
Specifies how the form border look like
StartPosition
Specifies at which position of the desktop the form has to be displayed.

Form Events:
          Certain events are triggered as a form is opened, closed, moved and so on.
Event
Description
Load
Triggers just before the form is loaded into the memory. It happens with Load()/Show() methods
Activated
When a form is activated in code or becomes visible through user movement amongst forms.
Deactivated
It is caused when the form loses focus
Closing
To examine the  method in which the used closed the form
Closed
Just prior to dispose event this event occurs, you could verity the closing intensions
Dispose
There is no terminate event in .net. it is used to provide any finalization code.

Windows Controls:
          The System.Windows.Forms.Control class is the base class for all controls that are to be created. This class is derived from System.ComponentModel.Component class.
Hierarchy of Control classes:
  • System.ComponentModel.Component
    • Control
      • ButtonBase
      • Button
    • ScrollableControl
      • ContainerControl
        • Form
Types of Controls:
Type
Controls
Command
Button, LinkLabel, NofityIcon, ToolBar
Menu
MainMenu, ContextMenu
Selection
CheckedListBox, ComboBox, ListBox, ListView, TreeView
Text
TextBox, RitchTextBox, Label, LinkLabel, StatusBar
Graphics
PictureBox, ImageList
Value
CheckBox, CheckedListBox, RadioButton
Date
DateTimePicker, MonthCalander
Grouping
Panel, GroupBox, TabControl
CommonDialog
Color, Font, OpenFile, SaveFile, Print, PrintPreview

Windows Controls:
Control
Description
Button
Control that can be clicked to perform some desired action.
CheckBox
Primarily used for displaying a binary state of an object. Clicking the check box causes it to toggle between a checked or unchecked state.
CheckListBox
List box with a column of check boxes.
ComboBox
A drop-down list of choices that operates similar to the list box. The primary difference is that the combo box is more compact and efficient with screen real estate.
DataGridView
An extremely powerful control that permits a program to bind to a data source.
DateTimePicker
Provides a capability to select a date and time without typing.
DomainUpDown
Permits a user to scroll through a list of data items that can only be shown one at a time.
Form
The main window of an application, a dialog, or a multiple-document interface (MDI) child. It provides all the capabilities for hosting child controls.
GroupBox
Houses a group of other controls often used to encapsulate a group of radio buttons. It can help organize a form and has a customizable title.
Label
Primarily used to display static text but can also contain
Images.
LinkLabel
The same as a label, but it can contain an URL that can be clicked to invoke an Internet connection.
ListBox
Holds selectable lists of data items. When the viewable portion of the list box is filled, a scrollbar appears so that all of its contained items may be selected.
ListView
Provides capabilities for multiple columns, column headers, column resizing, and list sorting It can also be configured in four different display modes. More Sophisticated than a list box.
MessageBox
Provides notifications to users on certain program events. It has a configurable message, title bar, icon, and button.
MonthCalendar
A visual calendar control.
NumericUpDown
The same as a DomainUpDown, with the restriction that its
contents are numeric.
Panel
Blank forms with little or no decoration that are used primarily for organization and form layout.
PictureBox
Displays an image.
ProgressBar
Used to display the status of an ongoing operation. It has a graph-ical indicator, set by a program to show the percentage of task completion.
RadioButton
Mutually exclusive buttons that permit users to make a choice. Also called option buttons.

RichTextBox
An enhanced text box control that provides more control over its text. It has the capability of creating Rich Text Format (RTF) files.
ScrollBar
Often used to help position the current location in a document
That’s too large to fit onscreen or in whatever space is available.
Splitter
Permit a user to resize multiple portions of a workspace. When the splitter is moved, one portion of the workspace gets larger, and others become smaller.
StatusBar
Performs multiple functions. Primarily it’s a place to notify users of a program’s status or other forms of current information.
TabControl
User interfaces that appear like file folder tabs. When selected, they open a specific page where the tab and content match.
TextBox
Allows a user to type text. They can be single line or multiline and have many capabilities for text manipulation such as selection, cut, copy, and paste.
Timer
Non visual controls that raise events at specified intervals. They can be used for such things as reminders or auto-save operations.
ToolBar
Permits a user to invoke selected operations in a program; similar in functionality to menus.
ToolTip
Helpful messages that appear when a cursor hovers over a control for a specified amount of time.
TrayIcon
Icons displayed on the icon tray of the window’s taskbar. They usually have different pictures to indicate the current state of a program.
TreeView
Displays items in a hierarchical fashion. It has a root node at the top of the tree and can have multiple branches and nodes. Traditionally, it has collapsible branches and is coordinated with another control to display details of selected nodes.







Menus
Most applications have a main menu, which is a quick way to access all the functionality of an application. Another popular feature of programs is to offer context-sensitive menus via right-click on parts of the program where they might make sense.
You can have more than one menu system per form which reduces the complexity of creating dynamic menus, and you can create context menus directly without designing them as top level menus first.

Menu Classes:
          Three menu classes are there that will use when creating menus.
MainMenu:    you use this class to create a standard windows associated menu bar at the top of a form.
ContextMenu: You use this class to define pop-up menus associated with particular controls
MenuItem: You use this class to define menu items within a MainMenu or a ContextMenu.

Creating a MainMenu at Design Time:
          When we add the MainMenu control it will be placed in the component tray. Once an instance of the control becomes part of your application, you will be presented with the first menu item a prompt to “Type Here”. The menu control leaves open space for us to add to the menu system at any time.
  • To create a menu separator, type a “hyphen(-)” in the “type here” prompt.
  • If you want to create sub menus, simply type in “type here” area that is displayed to the right of the current area. The control will add the appropriate arrows to indicate a sub menu.
  • The main menu is made up of MenuItem children objects. The hierarchy is then created between parent and child objects.
  • To create an access key for a menu item, select the menu item to which you would like to assign an access key. Type an “ampersand(&)” in-front of the letter that is to be underlined and is to function as the access key.
  • To assign a shortcut key in main menu system, select the menu item, access the properties window and select the “Shortcut” property. Select the appropriate shortcut key combination from the drop-down menu that appears.
Note: To suppress the display of the shortcut key in the menu, set the “showShortcut” property of the menu item to false. Other properties for the menu item are:
Ø  Checked – displays the menu item with a check mark.
Ø  DefaultItem – specifies the menu item as the default.
Ø  Enabled – Grays out the menu item and makes it inaccessible.
Creating Menus Programmatically:
          This example programmatically creates a Windows Forms ContextMenu and associates it with a control.
private void Form1_Load(object sender, System.EventArgs e)
{
    System.Windows.Forms.ContextMenu contextMenu1;
    contextMenu1 = new System.Windows.Forms.ContextMenu();
    System.Windows.Forms.MenuItem menuItem1;
    menuItem1 = new System.Windows.Forms.MenuItem();
    System.Windows.Forms.MenuItem menuItem2;
    menuItem2 = new System.Windows.Forms.MenuItem();
    System.Windows.Forms.MenuItem menuItem3;
    menuItem3 = new System.Windows.Forms.MenuItem();

    contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {menuItem1, menuItem2, menuItem3});
    menuItem1.Index = 0;
    menuItem1.Text = "MenuItem1";
    menuItem2.Index = 1;
    menuItem2.Text = "MenuItem2";
    menuItem3.Index = 2;
    menuItem3.Text = "MenuItem3";

    textBox1.ContextMenu = contextMenu1;
}

MDI Forms
          Multiple-Document Interface(MDI) applications allow you to display multiple documents at the same time with each document displayed in its own window under a container.
Creating a Parent Form:
          You can use the “IsMdiContainer” property of a form to make it an MDI Parent form. This holds a Boolean value.
Creating Child Forms:
          You can create child forms by setting the “MdiParent” property of a form to the name of the already created MDI parent.
          Sub AddDoc()
                   Form2  frm=new Form2();
                   Frm.MdiParemt=this;
                   Frm.Show();

          

ADO DOTNET

ADO.NET

One problem with ADO is that it was originally created as a connected database access object model. This means that developers primarily use a Recordset object while connected to the data source. Microsoft modified the recordset to allow disconnected access, but this solution did not work as well as if it had been designed as a disconnected data access model from the beginning. The recordset object can contain only one result set. This means we cannot relate result sets using a primary key / foreign key type of relationship and we cannot relate result sets from different data sources.
With .NET, Microsoft developed an entirely new data model that uses the provider wrapper technology but eliminates the old-style recordset object. That new data model is ADO.NET.
ADO.NET still uses Connection and Command types, but it replaces the Recordset with two data types- DataReader and DataSet objects.
The DataReader object provides connected data access. The DataSet, the core object of ADO.NET is an in-memory cache of disconnected data.
ADO.NET is a set of classes that allow .NET based applications to read and update information in databases and other data sources. You can access these classes through the System.Data namespace provided by the .NET framework.
ADO.NET provides consistent access to a wide variety of data sources including Microsoft SQL Server database, OLEDB compliant databases, non-relational sources such as Microsoft Exchange Server and XML documents.

Benefits of ADO.NET:
          ADO.NET provides many benefits to experienced developers including-
  1. Similar Programming model to that of ADO
  2. Designed for Disconnected Data-
ADO.NET is designed for working with disconnected data in a multitier environment.
It uses XML as the format for transmitting disconnected data, which makes it easier to communicate with client applications that are not based on windows.
  1. Intrinsic to the .NET Framework-
Because ADO.NET is intrinsic to the .NET Framework, you have all the advantages of using the .NET framework, including ease of cross-language development.
  1. Supports XML-
ADO and XML have previously been incompatible. ADO was based on relational data, and XML is based on hierarchical data. ADO.NET brings together these two data access techniques and allows you to integrate hierarchical and relational data, as well as alternate between XML and relational programming models.






ADO.NET Class Structure:
          We can divide the ADO.NET related classes into three groups.
·         .NET Provider Classes:
These classes interface with the database and provide some features for manipulating the retrieved data. Each data provider will have a different set of classes. For example, the SQL provider has sqlConnection, sqlCommand etc., we can easily pass data between these classes and the consumer classes.
·         Data Consumer Classes:
We use these classes for manipulating data. They are independent of the data source and we can manipulate data using these classes without an open connection to the databases.
·         Other .NET Framework Classes:
These classes are related to data handling but are not part of the System.Data namespace. For example, Data-Bound controls. These are part of the System.Windows.Forms namespace. We can easily pass data between these classes and Data Consumer Classes.





.NET Data Providers:
          In ADO.NET each particular type of data source has a .NET data provider. ADO.NET is providing managed providers for accessing data sources. They are:
·         SQL Server .NET Provider:
          System.Data.SqlClient.dll à Assembly
          sqlConnection, sqlCommand, sqlDataReader, sqlTransaction, sqlParameter are the classes under this namespace.
·         OLEDB .NET Provider:
This provider is used to access oracle, MS-Access and other data sources that support the Microsoft OLEDB data component interface.
System.Data.OleDb.dll àAssembly
OleDbConnection, OleDbCommand, OleDbDataReader etc., are the classes.
·         ODBC .NET provider:
System.Data.Odbc.dll à Assembly
OdbcConnection, OdbcCommand, OdbcDataReader etc., are the classes.
·         ORACLE .NET Provider:
System.Data.OraClient.dll à Assembly
OraConnection, OraCommand, OraDataReader etc., classes.

.NET Provider Classes:
          The provider classes for the SQL Server .NET Provider are derived from System.Data.SqlClient namespace. All begin with sql keyword. The classes for the OLEDB provider begin with OleDb etc., The classes for the OraClient provider begin with Ora and the classes with ODBC provider begins with Odbc. The classes are:
xxxConnection Class:
          The connection objects are the first objects that use and they are required before using any of the other ADO.NET provider objects. They provide the basic connection to your data source. If you are using a database that required a UserID and Password, or one on a remote network server, the connection object takes care of the details of establishing the connection and logging in.
Common Properties and methods of the Connection Class:
MemberName
Propter(p)/
Method(m)
Description
ConnectionString
P
Establishes the connection to the data source. Provider specific.
ConnectionTimeOut
P
Specifies the length of time(in sec) to attempt to connect
State
P
Get the state of the connection – Connected, Connecting, notConnected….
Provider
P
Used by oledb connection object to specify which oledb provider will be sued to communicate
Data Source/server
P
Server name
Initial catalog
P
Name of the database
Userid
P

Password
P

Interated Securith
P
Whether a connection is a secure connection
Open
M
Attempts to open the connection object based on the connection string.
Close
M
Closes the connection to the data source
BeginTransaction
M
Begins a database transaction.

Ex:       sqlConnection Con=new SqlConnection();
           
//using SQL Data Provider with Windows Authentication
            Con.ConnectionString=”Integrated Security=true;data source=(local);initial catalog=university”

//using SQL Data Provider with SQL Server Authentication
            Con.ConnectionString=”Integrated Security=true;data source=(local);initial catalog=university;uid=sqlclass;pwd=sql”

//using OleDb Data Provider
            Con.ConnectionString=”provider=sqloledb;data source=(local);intitial catalog=university;uid=;pwd=”;
            Con.Open();

//using Oracle
            OleDbConnection oleCon=new OleDbConnection();
             OleCon.ConnectionString=”provider=msdaora.1;userid=; pwd=”;
             OleCon.open()

XXXCommand Class:
            You can use the ADO.NET command object to execute commands and optionally, to return data from a data source.
Steps in using Command object:
1.    create a command object.
2.    Use the ‘CommandType’ property to specify the type of command to be executed.
CommandType.StoredProcedure
CommandType.Text
CommandType.Table
3.    Use ‘CommandText’ property and specify the command to be executed in case of Text type and name of the object in case of stored procedure or table name.
4.    Use one of the Execute menthod to execute the command.

Executing Commands:
            You can execute a command within a valid and open connection. The command object provides 3 methods that you can use to execute commands.
ExecuteReader():
            Use this method when the query will return a stream of data such as a Select Statement returning a set of records. This method returns the records in a DataReader object.
ExecuteScalar():
            Use this method when the query will return a singleton value. For example, a select statement returning an aggregate value. It executes the query and returns the first column of the first row in the result set, ignoring any other data that is returned.
ExecuteNonQuery():
            Use this method when the query will not return a result;ex: insert statement.
Ex:
            sqlCommand cmd=new sqlCommand();
            cmd.CommandType=CommandType.Text;
            cmd.CommandText=”select * from emp”;
            sqlDataReader dr;
            dr=cmd.ExecuteReader();

DataReader Class:
            DataReader object is used to create a read-only, forward-only stream of data. This is an efficient method for accessing data that you only need to read through code. You can improve the app performance by using this object. Because, it holds only a single row at a time in memory instead of caching the entire set of records.

Reading Data:
            You can instantiate the DataReader object by using the ExecuteReader method of command object. After you create the DataReader, you can call the “Read” method to obtain data in the rows. You can access the columns by name, ordinal number or native type in conjunction with ordinal number.
            Ex: While dr.Read()
                        {
                                    ------
                        }
            You must ensure that you sued the ‘Close’ method of the DataReader object before accessing any output or return parameter from a StoredProcedure.

Retrieving Data:
Assume that dr is the DataReader, then we can use any one of the following ways to retrieve the data.
dr.Item[0];
dr[0];
dr[“Empid”];
dr.GetString[0];
Using Command Object with Stored Procedure:
     I.        Create a Command object
sqlCommand cmd=new sqlCommand();
    II.        Set the CommandType property of command object to stored proecure.
cmd.CommandType=CommandType.StoredProcedure;
  III.        Specify the procedure name in CommandText property.
cmd.CommandText=”spGetEmployee”;
   IV.        Use the sqlParameter class to create a parameter object depending on the type and direction of the parameter in the procedure
sqlParameter param1=new sqlParameter(“@eid”,sqlDbType.int);
param1.Direction=ParameterDirection.Input;
    V.        Set the value of the parameter;
Param1.Value=Convert.ToInt32(txtEmpid.Text);
   VI.        Add the parameter to the parameter Collection.
cmd.Parameters.Add(param1);
 VII.        Execute the command object;
dr=cmd.ExectueReader();

DataSet
            DataSets are the primary objects that you will work with when accessing disconnected sets of data. They are similar in concept to groups of ADO disconnected recordsets, but in ADO.Net there are many enhancements including the ability to relate tables together.
DisConnected Data in RDO and ADO:
            RDO and ADO introduced the concept of disconnected data. This was implemented so that you could retrieve a set of records, disconnected from the data source, and work with the data locally. You could reconnect and submit your changes to the database. The recordsets were marshaled between the tiers as COM objects, requiring that both the server and client computer could handle COM Components
Disconnected Data in ADO.NET:
            ADO.Net is a designed for use in the internet world, where as COM may not be supported by all tiers, and may not be transmitted through fire walls.  ADO.Net uses XML as its transmission format. This is a text based format. It avoids the problems associated with the transmission of COM objects and ensuring true cross-platform interoperability.
            ADO.Net provides you with a new object for the caching of data on the client computer. This object is known as “DataSet”. This subject is automatically disconnected from the datasource but maintain the ability to later update the source based on changes made at the client.
            DataSet acts like in-memory database for the client application by maintaining collection of tables belonging to different data sources in the form of XML Storage.
            Dataset is always disconnected and the information will be filled into the dataset.


Creating DataSets:
Syntax:
            DataSet ds=new DataSet();     (or) 
            DataSet ds=new DataSet(“Table1”);

Populating DataSets:
            You can use the DataAdapter objects “Fill” method to access data stored in the datasource, and store the data in DataTables within a DataSet in your application.
Syn:     DataAdapter1.Fill(DataSetName,TableName)
Ex:       da.Fill(ds,”Table1”);

DataAdapter:
            You can use the DataAdapter to exchange data between a data source and a DataSet. You can use it to retrieve appropriate data and insert it into DataTable objects within a DataSet and to update changes from the DataSet back to the datasource.
Creating a DataAdapter:
            Ex: sqlDataAdapter da=new sqlDataAdapter(“Select * from table1”,con)
Fill method is used to populate the dataset with datasource information.
Update method is used to save the changes from dataset back to the datasource.

The Fill method will perform the following tasks:
·         It will establish the connection to the database server
·         It sends the Select Statement to the database server for execution
·         It creates a table in the dataset and gets the information from database server using implicitly DataReader
·         It will closes the connection.

Updating Data in DataSet:
            After you have created a DataSet of DataTables, you might want to add, update and delete data. Any changes you  make to the data are stored in memory and later used to apply changes to the data source.

Adding Rows:
1.    Instantiate a DataRow object by using ‘NewRow’ method tof the DataTable
2.    Populate the columns with data.
3.    Call the ‘Add’ method of the DataRows collection, passing the DataRow object.

Editing Rows:
1.    Call the BeginEdit method of the row
2.    Change the data in the Columns
3.    Call EndEdit or CancelEdit to accept or reject changes

Deleting Data:
            Use either of the following methods to delete a row.
·         Remove
            Call the Remove method of the DataRow collection. This permanently removes the row from the dataset
·         Delete
            Call the Delete method of the DataRow object. This only makes the row for deletion in the dataset and calling reject changes will undo the deletion.

Confirming Changes:
            To update the DataSet, you use the appropriate method to edit the table and then you call AcceptChanges or RejectChanges for the individual rows or for the entire table.
            You can discover whether any changes have been made to a row since AcceptChanges was last called by querying its ‘RowState’ property. It contains the following values.
Enumeration
Desc
Value
UnChanged
No changes have been made
2
Added
The row has been added to the table
4
Modified
Something in the row has been changed
16
Deleted
The row has been deleted by the delete method
8
Detached
The row has been deleted with ‘Remove’ method or row has been created, but the add method has not been called
1


Updating Data at the Source:
            After you have updated the tables in your dataset, you will want to replicate those changes to the underlying data source. To do this, you use the ‘Update’ method of the DataAdatper object.
            The Update method like fill method takes two parameters.
1.    The Dataset in which the changes have been made
2.    The name of the table in which changes are made.
            This method determines the changes to the data and execute appropriate SQL Command against the source data.

Automatically Generating Changes:
            If your datatable is generated from only one table in the datasource, you can use the commandBuilder object to automatically create the InsertCommand, DeleteCommand, UpdateCommand properties
Ex:
            sqlCommandBuilder cb=new sqlCommandBuilder(da);

            da.Update(ds,”table1”);