ASP[1].NET 3.5

download ASP[1].NET 3.5

of 29

Transcript of ASP[1].NET 3.5

  • 8/8/2019 ASP[1].NET 3.5

    1/29

    ASP.NET State Management

    HTTP is a stateless protocol. After every web request, the client disconnects from theserver, and the ASP.NET engine discards the objects that were created for the page. So that State

    Management techniques used to maintaining information on the server and on the client. Youchoose the right option depending on the data you need to store, the length of time you want tostore it, the scope of your data (whether it's limited to individual or shared across multiplerequests), and additional security and performance considerations.

    1. View State2. Query String3. Custom Cookies4. Session State5. Application State6. Profile

    7. Caching

    1. View State

    Allowed data types: All serializable .NET data types.Storage location: A hidden field in the current web page.Lifetime: Retained permanently for postbacks to a single page.Scope: Limited to the current page.Security: Tamper-proof by default but easy to read.Performance: Storing a large amount of information will slow transmission but will not

    affect server performance.Typical use: Page-specific settings (Maintaining state/information for each page).

    ViewState["Counter"] = 1;int counter;counter = (int) ViewState["Counter"];

    2. Query String

    Allowed data types: A limited amount of string data.Storage location: The browser's URL string.Lifetime: Lost when the user enters a new URL or closes the browser.Scope: Limited to the target page.Security: Clearly visible and easy for the user to modify.Performance: None, because the amount of data is trivial.Typical use: Sending information from current page to target page.

    int recordID = 10;Response.Redirect("newpage.aspx?recordID="+ recprdID.ToString());string ID = Request.QueryString["recordID"];

  • 8/8/2019 ASP[1].NET 3.5

    2/29

    URL Encoding

    Its allow special characters [e.g. #, $, etc.] to use Query String. HttpServerUtility class encode ordecode your data automatically.

    string name = "Test&Test##Test";Response.Redirect("home.aspx?name=" + Server.UrlEncode(name));Response.Write(Server.UrlDecode(Request.QueryString["name"]));

    3. Cookies

    Allowed data types: String data.Storage location: The client's computer.Lifetime: Set by the programmer.Scope: The whole ASP.NET application.Security: Insecure and can be modified by the user.Performance: None, because the amount of data is trivial.Typical use: Personalization preferences for a website.

    //Create the cookie object HttpCookie cookie = newHttpCookie("Preferences"); //Set Value

    cookie["Language"] = "English"; //Add another value

    cookie["country"] = "US"; //Add it to the current response

    Response.Cookies.Add(cookie); //This cookie lives for 1 year

    cookie.Expires = DateTime.Now.AddYears(1);

    HttpCookie cookie1 = Request.Cookies["Preferences"];

    if (cookie1 != null)Response.Write(cookie1["Language"] );

    4. Session State

    Allowed data types: All serializable .NET data types. Nonserializable types are supported ifyou are using the default in-process state service.

    Storage location: Server memory (by default), or a dedicated database, depending onthe mode you choose.

    Lifetime: Times out after a predefined period (usually 20 minutes but can be alteredglobally or programmatically).

    Scope: The whole ASP.NET application.Security: Secure.Performance: Storing a large amount of information can slow down the server.Typical use: Maintain information/state for individual users.

    Syntax of adding item to the collection.Session["ProductDataset"] = dsProducts;dsProducts = (DataSet) Session["ProductDataSet"];

  • 8/8/2019 ASP[1].NET 3.5

    3/29

    It allows information to be stored in one page and accessed in another and it supports any type ofobjects. Every time you make a new request, ASP.NET generates a new session ID.

    Session Architecture

    Session management is not part of the HTTP standard. As a result, ASP.NET needs to do someextra work to track session information and bind it to the appropriate response.ASP.NET tracks each session using a unique 120-bit identifier. ASP.NET uses a proprietaryalgorithm to generate this value [Session Id]. This ID is the only piece of information that istransmitted between the web server and the client. When the client presents the sessionID,ASP.NET looks up the corresponding session, retrieves the serialized data from the state server,converts it to live objects, and places these objects into special collection so they can be accessedin code. This process takes place automatically.

    Class: System.Web.SessionState.HttpSessionStateSession state can be lost in several ways:>> Close and restarts the browser>> Access the same page through a different browser window.>> Session Time out.>> Calling Session.Abandon()

    How the session ID is tracked from one request to the next?You can accomplish this in two ways1. Using cookies: In this case, the session ID is transmitted in a special cookie [namedASP.NET_SessionId], which ASP.NET creates automatically when the session collection isused. This is default.2. Using modified URLs: In this case, the session ID is transmitted in a specially modified URL.This allows you to create applications that use session state with clients that don't supportcookies.

    Key methods and properties of the HttpSessionState Class

    Count: The number of items in the current session collection.IsCookieless: Identifies whether this session is tracked with a cookie or with modified URLsIsNewSession: Identifies whether this session was just created for the current request.Mode: Provides an enumerated value that explains how ASP.NET stores session stateinformation. This storage mode is determined based on the web.config configuration settings.SessionID: Provides a string with the unique session identifier for the current client.E.g. SessionId = 10k20j39did9o9930dThe following are the collections of the created Session.Session["a"]Session["b"]

  • 8/8/2019 ASP[1].NET 3.5

    4/29

    Timeout:

    Abandon(): Cancels the current session immediately and releases all the memory it occupied.Clear(): Removes all the session items but doesn't change the current session identifier.

    Off: This setting disables session state management for every page in the application.InProc: Default option. It instructs ASP.NET to store information in the current applicationdomain.StateServer: Use a separate Windows service for state management.SQLServer: Use a SQL Server database to store session information. as identified by thesqlConnectionString attribute.

    5. Application State

    Allowed data types: All .NET dataStorage location: Server memoryLifetime: The lifetime of the application (typically, until the server is rebooted).Scope: The whole ASP.NET application. Unlike most other types of methods, application data is

    global to all users.Security: Very secure, because data is never transmitted to the client.Performance: Storing a large amount of information can slow down the server, because

    this data will never time out and be removed.Typical use: Storing any type of global data.

    6. Profiles

    Allowed data types: All serializable .NET data types.Storage location: A back-end database.Lifetime: PermanentScope: The whole ASP.NET application. May also be accessed by other applications.

  • 8/8/2019 ASP[1].NET 3.5

    5/29

    Security: Very secure.Performance: Large amount of data can be stored easily.Typical use: Store large amount of information.

    7. Caching

    Allowed data types: All .NET data types.Storage location: Server memory.Lifetime: Depends on the expiration policy you setScope: The same as application state (global to all users and all pages).Security: Very secure, because data is never transmitted to the client.Performance: Storing a large amount of information may force out other, more usefulcached information.Typical use: Storing data retrieved from a database.

    Page.IsPostBack Property

    Gets a value indicating whether the page is being loaded in response to a client postback, or if itis being loaded and accessed for the first time.

    Property Value

    True if the page is being loaded in response to a client postback; otherwise, false.

    Overview of ADO.NET

    ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as well asdata sources exposed through OLE DB and XML. Data-sharing consumer applications can use

    ADO.NET to connect to these data sources and retrieve, manipulate, and update data.

    ADO.NET includes .NET Framework data providers for connecting to a database, executingcommands, and retrieving results. Those results are either processed directly, or placed in anADO.NET DataSet object in order to be exposed to the user in an ad-hoc manner, combinedwith data from multiple sources, or remoted between tiers. The ADO.NET DataSet object can

  • 8/8/2019 ASP[1].NET 3.5

    6/29

    also be used independently of a .NET Framework data provider to manage data local to theapplication or sourced from XML.

    The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes

    found in System.Xml.dll. When compiling code that uses the System.Data namespace, referenceboth System.Data.dll and System.Xml.dll.

    ADO.NET Architecture

    ADO.NET uses a multilayered architecture.a) Connected Layerb) Disconnected Layer

    ADO.NET Components

    The ADO.NET components have been designed to factor data access from data manipulation.There are two central components of ADO.NET that accomplish this: the DataSet, and the .NETFramework data provider, which is a set of components including the Connection, Command,DataReader, and DataAdapter objects.

    The ADO.NET DataSet is the core component of the disconnected architecture of ADO.NET.The DataSet is explicitly designed for data access independent of any data source. As a result itcan be used with multiple and differing data sources, used with XML data, or used to managedata local to the application. The DataSet contains a collection of one or more DataTableobjects made up of rows and columns of data, as well as primary key, foreign key, constraint, andrelation information about the data in the DataTable objects.

    Using ADO.NET, XML, and LINQ with ASP.NET

    http://msdn.microsoft.com/en-us/library/zb0sdh0b(VS.71).aspxhttp://msdn.microsoft.com/en-us/library/zb0sdh0b(VS.71).aspx
  • 8/8/2019 ASP[1].NET 3.5

    7/29

    Using ADO.NET Disconnected Classes

    Disconnected data access classes: DataTable and DataSet

  • 8/8/2019 ASP[1].NET 3.5

    8/29

    DataTable Object

    The DataTable Object represents tabular data as rows, columns and constraints. Use theDataTable object to hold data in memory while performing disconnected data operations.

    classProgram{

    privateDataTable getDataTable(){

    //Create the DataTable named "employee".

    DataTable employee = newDataTable("Employee");

    //Add the DataColumn using all properties DataColumn eid = newDataColumn("Eid");

    eid.DataType = typeof(string);eid.MaxLength = 10;eid.Unique = true;eid.AllowDBNull = false;eid.Caption = "EID";employee.Columns.Add(eid);

    //Add the DataColumn using defaults DataColumn firstName = newDataColumn("FirstName");

    firstName.MaxLength = 35;firstName.AllowDBNull = false;employee.Columns.Add(firstName);

    DataColumn lastName = newDataColumn("LastName");lastName.AllowDBNull = false;employee.Columns.Add(lastName);

    //Add the decimal DataColumn using defaults

  • 8/8/2019 ASP[1].NET 3.5

    9/29

    DataColumn salary = newDataColumn("Salary",typeof(decimal));salary.DefaultValue = 00.000M;employee.Columns.Add(salary);

    //Derived column using Expression

    DataColumn lastNameFirstName = newDataColumn("LastNameFirstName");lastNameFirstName.DataType = typeof(string);lastNameFirstName.MaxLength = 70;lastNameFirstName.Expression = "lastName + ',' + firstName";employee.Columns.Add(lastNameFirstName);

    //Set the Primary keyemployee.PrimaryKey = newDataColumn[] {eid};

    //Add new DaataRow by Creating the DataRow first DataRow newEmployee = employee.NewRow();

    newEmployee["Eid"] = "1";newEmployee["FirstName"] ="Peter";

    newEmployee["LastName"] ="Ferna";newEmployee["Salary"] = 5000.000;employee.Rows.Add(newEmployee);return employee;

    }

    staticvoid Main(string[] args){

    Program p = newProgram();p.getDataTable();

    Console.ReadLine();}

    }

    Using the DataTable with XML Data

    staticvoid Main(string[] args){

    DataSet ds = newDataSet(); Program p = newProgram();

    ds.Tables.Add(p.getDataTable());ds.WriteXml("E:\\Prakash\\CSharp Windows

    Application\\InterfaceExample\\InterfaceExample\\XMLFile1.xml"); Console.ReadLine();

    }

    DataView

    staticvoid Main(string[] args){

  • 8/8/2019 ASP[1].NET 3.5

    10/29

    DataSet ds = newDataSet(); Program p = newProgram();

    ds.Tables.Add(p.getDataTable()); //Sort and Display DataView view = newDataView(ds.Tables[0]);

    view.Sort = "LastName ASC, FirstName ASC, Salary DESC";view.RowFilter = "LastName like 'A%' and Salary > 15";GridView.DataSource = view;GridView1.DataBind();

    Console.ReadLine();

    }

  • 8/8/2019 ASP[1].NET 3.5

    11/29

    Using ADO.NET Connected Classes

    The other core element of the ADO.NET architecture is the .NET Framework data provider,whose components are explicitly designed for data manipulation and fast, forward-only, read-only access to data. The Connection object provides connectivity to a data source. TheCommand object enables access to database commands to return data, modify data, run storedprocedures, and send or retrieve parameter information. The DataReader provides a high-performance stream of data from the data source. Finally, the DataAdapter provides the bridgebetween the DataSet object and the data source. The DataAdapter uses Command objects toexecute SQL commands at the data source to both load the DataSet with data, and reconcilechanges made to the data in the DataSet back to the data source.

    .NET Framework Data Providers

    A .NET Framework data provider is used for connecting to a database, executing commands, andretrieving results. Those results are either processed directly, or placed in an ADO.NET DataSetin order to be exposed to the user in an ad-hoc manner, combined with data from multiplesources, or remoted between tiers. The .NET Framework data provider is designed to belightweight, creating a minimal layer between the data source and your code, increasingperformance without sacrificing functionality.

    The following table outlines the four core objects that make up a .NET Framework data provider.

    Object Description

    Connection Establishes a connection to a specific datasource.

    Command Executes a command against a data source.Exposes Parameters and can execute within thescope of a Transaction from a Connection.

    DataReader Reads a forward-only, read-only stream of datafrom a data source.

    DataAdapter Populates a DataSet and resolves updates withthe data source.

    The .NET Framework Data Provider for OLE DB

    The following table shows the providers have been tested with ADO.NET.

    Driver Provider

    SQLOLEDB Microsoft OLE DB Provider for SQL Server

    MSDAORA Microsoft OLE DB Provider for Oracle

    http://msdn.microsoft.com/en-us/library/a6cd7c08(VS.71).aspxhttp://msdn.microsoft.com/en-us/library/a6cd7c08(VS.71).aspx
  • 8/8/2019 ASP[1].NET 3.5

    12/29

    Microsoft.Jet.OLEDB.4.0 OLE DB Provider for Microsoft Jet

    Choosing a .NET Framework Data Provider

    Depending on the design and data source for your application, your choice of .NET Framework

    data provider can improve the performance, capability, and integrity of your application. Thefollowing table discusses the advantages and limitations of each .NET Framework data provider.

    Provider Notes

    .NET Framework Data

    Provider for SQL

    Server

    Recommended for middle-tier applications using Microsoft SQL Server7.0 or later.

    Recommended for single-tier applications using Microsoft Data Engine(MSDE) or Microsoft SQL Server 7.0 or later.

    Recommended over use of the OLE DB Provider for SQL Server

    (SQLOLEDB) with the .NET Framework Data Provider for OLE DB.

    For Microsoft SQL Server version 6.5 and earlier, you must use theOLE DB Provider for SQL Server with the .NET Framework DataProvider for OLE DB.

    .NET Framework Data

    Provider for OLE DB

    Recommended for middle-tier applications using Microsoft SQL Server6.5 or earlier, or any OLE DB provider that supports the OLE DBinterfaces listed in OLE DB Interfaces Used by the .NET FrameworkData Provider for OLE DB (OLE DB 2.5 interfaces are not required).

    For Microsoft SQL Server 7.0 or later, the .NET Framework Data

    Provider for SQL Server is recommended.

    Recommended for single-tier applications using Microsoft Accessdatabases. Use of a Microsoft Access database for a middle-tierapplication is not recommended.

    .NET Framework Data

    Provider for ODBC

    Recommended for middle-tier applications using ODBC data sources.

    Recommended for single-tier applications using ODBC data sources.

    Note The .NET Framework Data Provider for ODBC isnot included in the .NET Framework version 1.0. If you

    require the .NET Framework Data Provider for ODBCand are using the .NET Framework version 1.0, you candownload the .NET Framework Data Provider for ODBCat http://msdn.microsoft.com/downloads. The namespacefor the downloaded .NET Framework Data Provider forODBC is Microsoft.Data.Odbc.

    .NET Framework Data Recommended for middle-tier applications using Oracle data sources.

    http://msdn.microsoft.com/en-us/library/cwctxe7a(VS.71).aspxhttp://msdn.microsoft.com/en-us/library/cwctxe7a(VS.71).aspxhttp://msdn.microsoft.com/en-us/library/cwctxe7a(VS.71).aspxhttp://msdn.microsoft.com/en-us/library/cwctxe7a(VS.71).aspx
  • 8/8/2019 ASP[1].NET 3.5

    13/29

    Provider for Oracle

    Recommended for single-tier applications using Oracle data sources.

    Supports Oracle client software version 8.1.7 and later.

    The .NET Framework Data Provider for Oracle classes are located inthe System.Data.OracleClient namespace and are contained in theSystem.Data.OracleClient.dll assembly. You need to reference boththe System.Data.dll and the System.Data.OracleClient.dll whencompiling an application that uses the data provider.

    System.Data.Common Namespace

    The System.Data.Common namespace contains classes shared by the .NET Framework data

    providers.

    A .NET Framework data provider describes a collection of classes used to access a data source,such as a database, in the managed space. Supported providers include the .NET FrameworkData Provider for ODBC, the .NET Framework Data Provider for OLEDB, the .NET FrameworkData Provider for Oracle, and the .NET Framework Data Provider for SQL Server. The classes inSystem.Data.Common are intended to give developers a way to write ADO.NET code that willwork against all .NET Framework data providers.

    For conceptual information about how to use this namespace when programming with the.NETFramework, see Writing Provider Independent Code with ADO.NET.

    BASE CLASS SQLCLIENT CLASSES GENERIC INTERFACE

    DbConnection SqlConnection IDBConnectionDbCommand SalCommand IDBCommandDbDataReader SqlDataReader IDataReader/IDataRecordDbTransaction SqlTransaction IDbTransactionDbParameter SqlParameter IDBDataParameter DbDataAdapter SqlDataAdapter IDbDataAdapter

    appSettings Element

    Contains custom application settings, such as file paths, XML Web service URLs, or anyinformation that is stored in the.ini file for an application.

    http://msdn.microsoft.com/en-us/library/t9f29wbk.aspxhttp://msdn.microsoft.com/en-us/library/t9f29wbk.aspx
  • 8/8/2019 ASP[1].NET 3.5

    14/29

    ====================================================================string sSmtpServer =System.Configuration.ConfigurationManager.AppSettings["SmtpServer"];

    ConnectionStrings Element

    Specifies a collection of database connection strings, as name/value pairs, for ASP.NETapplications and features.

    Adds a connection string as a name/value pair to the collection of

    connection strings. Removes all references to inherited connection strings, allowing

    only the connection strings that are added by the current addelement. Removes a reference to an inherited connection string from the

    collection of connections strings.

    http://msdn.microsoft.com/en-us/library/htw9h4z3.aspxhttp://msdn.microsoft.com/en-us/library/htw9h4z3.aspx
  • 8/8/2019 ASP[1].NET 3.5

    15/29

    string ConnectionString =WebConfigurationManager.ConnectionString["NorthWind"].ConnectionSrting;

    CommondType.Text: The command will execute a direct SQL statement.

    CommandType.StordProcedure: The command will execute a stored procedure in the datasource.

    SqlCommand cmd = new SqlCommand();

    cmd.Connection = con;

    cmd.CommandType = CommandType.Text; //[Default]

    cmd.CommandText = "SELECT * FORM Employees";

    OR

    SqlCommand cmd = new SqlCommand("SLECT * FROM Employee", con);

    ===============================================================

    SqlCommand cmd = new SqlCommand("SP_GetEmployee", con);

    cmd.CommandType = CommandType.StoredProcedure;

    1. SqlCommand.ExecuteNonQuery Method

    Executes a Transact-SQL statement against the connection and returns the number of rowsaffected. E.g. SELECT, INSERT, DELETE, UPDATE etc.

    2. SqlCommand.ExecuteScalar Method

    Executes the query, and returns the first column of the first row in the result set returned by thequery. Additional columns or rows are ignored.

    3. SqlCommand.ExecuteReaderMethod

  • 8/8/2019 ASP[1].NET 3.5

    16/29

    Executes a SELECT query and returns a DataReader object that wraps a read-only, forward-onlycursor.

    Calling Stored Procedures

    Stored procedures have many benefits:

    1. They are easier to maintain.

    2. They allow you to implement more secure database usage.

    3. They can improve performance.

    CREATE PROCEDURE InsertEmployee

    @TitleOfCourtesy varchar(25),

    @LastName varchar(20),

    @FirstName varchar(10),

    @EmployeeID int OUTPUT

    AS

    INSERT INTO Employee(TitleOfCourtesy, LastName, FirstName)

    SET @EmployeeID = @@IDENTITY

    string connectionString =WebConfigurattionManager.ConnectionStrings["Northwind"].ConnectionString;

    SqlConnection con = new Sqlconnection(connectionString);

    SqlCommand cmd = new SqlCommand("InsertEmployee", con)

  • 8/8/2019 ASP[1].NET 3.5

    17/29

    cmd.CommandType = CommandType.StoredProcedure;

    cmdParameters.Add(new SqlParameter("@TitleOfCourtesy", SqlDbType.NVarChar, 25));

    cmd.Parameters["TitleOfCourtesy"].value = title;

    cmd.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 4));

    cmd.Parameters["@EmployeeID"].Direction = ParameterDirection.Output;

    int numAff = cmd.ExecuteNonQuery();

    Transactions

    A transaction consists of a single command or a group of commands that execute as a package.Transactions allow you to combine multiple operations into a single unit of work. If a failure

    occurs at one point in the transaction, all of the updates can be rolled back to their pre-transactionstate.

    Transactions in ADO.NET are used when you want to bind multiple tasks together so that

    they execute as a single unit of work.

  • 8/8/2019 ASP[1].NET 3.5

    18/29

    Update Checked Status

    WebService wsObj = newWebService();protectedvoid Page_Load(object sender, EventArgs e){

    Label2.Text = "Page created at: " + DateTime.Now.ToLongTimeString(); if (!Page.IsPostBack)

    { DataSet ds = newDataSet();

    ds = wsObj.WSGetInfo();GridView1.DataSource = ds;GridView1.DataBind();CheckBoxList1.DataSource = ds;CheckBoxList1.DataTextField = "Name";CheckBoxList1.DataValueField = "Sl";CheckBoxList1.DataBind();RadioButtonList1.DataSource = ds;RadioButtonList1.DataTextField = "Name";RadioButtonList1.DataValueField = "Sl";RadioButtonList1.DataBind();

    }}

    protectedvoid Timer1_Tick(object sender, EventArgs e){//lb.Text = "Panel refreshed at: " + DateTime.Now.ToLongTimeString();Label1.Text = "Panel refreshed at: " +

    DateTime.Now.ToLongTimeString(); DataSet ds = newDataSet();

    ds = wsObj.WSGetInfo();GridView1.DataSource = ds;GridView1.DataBind();

    }

    protectedvoid Button1_Click(object sender, EventArgs e){

    //wsObj.WSUpdateStatus(1, 1);

    int i; //for (i = 0; i < CheckBoxList1.Items.Count - 1; i++) //{ // if (CheckBoxList1.Items[i].Selected) // wsObj.WSUpdateStatus(1,Convert.ToInt32(CheckBoxList1.Items[i].Value)); // else

  • 8/8/2019 ASP[1].NET 3.5

    19/29

    // wsObj.WSUpdateStatus(0,Convert.ToInt32(CheckBoxList1.Items[i].Value)); //}

    //for (i = 0; i < RadioButtonList1.Items.Count - 1; i++) //{

    // if (RadioButtonList1.Items[i].Selected) // wsObj.WSUpdateStatus(1,Convert.ToInt32(RadioButtonList1.Items[i].Value)); // else // wsObj.WSUpdateStatus(0,Convert.ToInt32(RadioButtonList1.Items[i].Value)); //}

    for (i = 0; i < GridView1.Rows.Count - 1; i++){

    GridViewRow row = GridView1.Rows[0]; bool isChk = ((CheckBox) row.FindControl("CheckBox2")).Checked; HiddenField hf = (HiddenField)row.FindControl("id"); int val = Convert.ToInt32(hf.Value);

    if(isChk)wsObj.WSUpdateStatus(1, val);

    elsewsObj.WSUpdateStatus(0, val);

    }}

    protectedvoid Button2_Click(object sender, EventArgs e){

    //"~/UserControls/WebUserControl.ascx" string path = Server.MapPath("~/Log/LogFile.txt"); StreamWriter writerObj; if (File.Exists(path))

    {

    writerObj = File.AppendText(path);} else

    {writerObj = File.CreateText(path);

    }writerObj.Write("PtL!");writerObj.Close();

    }

    publicDataView bindGrid(){

    DataSet ds = newDataSet(); DataView dv = newDataView();

    ds = wsObj.WSGetInfo(); if (ViewState["SortExp"] != null)

    {dv = new DataView(ds.Tables[0]);dv.Sort = ViewState["SortExp"].ToString();

    } else

    {

  • 8/8/2019 ASP[1].NET 3.5

    20/29

    dv = ds.Tables[0].DefaultView;}

    return dv;}

    protectedvoid GridView1_PageIndexChanging(object sender,

    GridViewPageEventArgs e){

    GridView1.PageIndex = e.NewPageIndex;GridView1.DataSource = bindGrid();GridView1.DataBind();

    } protectedvoid GridView1_Sorting(object sender, GridViewSortEventArgs e)

    { //string aa = e.SortExpression; if (ViewState["SortExp"] != null)

    { if (ViewState["Exp"].ToString() == "Asc")

    {

    ViewState["SortExp"] = e.SortExpression + " Desc";ViewState["Exp"] = "Desc";

    } else

    {ViewState["SortExp"] = e.SortExpression + " Asc";ViewState["Exp"] = "Asc";

    }}

    else{

    ViewState["SortExp"] = e.SortExpression + " Asc";ViewState["Exp"] = "Asc";

    }

    GridView1.DataSource = bindGrid();GridView1.DataBind();

    }}

    Untitled Page

  • 8/8/2019 ASP[1].NET 3.5

    21/29

    Link

  • 8/8/2019 ASP[1].NET 3.5

    22/29

    using System;

    using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;

    publicpartialclass_Default : System.Web.UI.Page{

    MyService.Service objService = new MyService.Service();

    protectedvoid Page_Load(object sender, EventArgs e){

    if (!IsPostBack){

    //GridViewRow row = GridView1.DataBinder();

    }}

    protectedvoid Button1_Click(object sender, EventArgs e){

    int i;

    DataSet ds = newDataSet(); DataTable dt = newDataTable("TestTable");dt.Columns.Add(newDataColumn("Sl",

    System.Type.GetType("System.Int32")));dt.Columns.Add(newDataColumn("Name",

    System.Type.GetType("System.String")));dt.Columns.Add(newDataColumn("Address",

    System.Type.GetType("System.String")));dt.Columns.Add(newDataColumn("status",

    System.Type.GetType("System.Boolean"))); for (i = 0; i < GridView1.Rows.Count; i++)

    { GridViewRow row;

    row = GridView1.Rows[i];

    bool status = ((CheckBox) row.FindControl("chkStatus")).Checked;

    HiddenField hidText = (HiddenField)row.FindControl("chkHidden");

    if (status){

    DataRow dr = dt.NewRow();dr["Sl"] = Convert.ToInt32(GridView1.Rows[i].Cells[0].Text);

  • 8/8/2019 ASP[1].NET 3.5

    23/29

    dr["Name"] = GridView1.Rows[i].Cells[0].Text;dr["Address"] = GridView1.Rows[i].Cells[0].Text;dr["status"] = status;dt.Rows.Add(dr);

    }

    }

    if (dt.Rows.Count > 0){

    ds.Tables.Add(dt);objService.WSWriteXML(ds);

    }}

    protectedvoid GridView1_PageIndexChanging(object sender,GridViewPageEventArgs e)

    {GridView1.PageIndex = e.NewPageIndex;DataBinder();

    } protectedvoid GridView1_Sorting(object sender, GridViewSortEventArgs e)

    {Response.Write(e.SortDirection.ToString() + " ========== " +

    e.SortExpression.ToString());

    }

    protectedvoid GridView1_RowEditing(object sender, GridViewEditEventArgse)

    {GridView1.EditIndex = e.NewEditIndex;

    }

    protectedvoid GridView1_RowUpdating(object sender,GridViewUpdateEventArgs e){

    //TextBox txtName = e.Keys[e.]}

    protectedvoid GridView1_RowDeleting(object sender,GridViewDeleteEventArgs e)

    {

    } protectedvoid GridView1_RowCommand(object sender,GridViewCommandEventArgs e)

    {

    } protectedvoid GridView1_RowCancelingEdit(object sender,GridViewCancelEditEventArgs e)

    {GridView1.EditIndex = -1;

    }

    publicvoid DataBinder()

  • 8/8/2019 ASP[1].NET 3.5

    24/29

    {GridView1.DataSource = objService.WSGetInfo();GridView1.DataBind();

    }

    }

    using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;

    using System.Web.UI.HtmlControls;

    publicpartialclassDataSetRelation : System.Web.UI.Page{ DataSet dataSet; protectedvoid Page_Load(object sender, EventArgs e)

    { //http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx

    MakeDataTables();}

    privatevoid MakeDataTables(){

    // Run all of the functions.MakeParentTable();MakeChildTable();MakeDataRelation();BindToDataGrid();

    }

    privatevoid MakeParentTable(){

    // Create a new DataTable.

    DataTable table = newDataTable("ParentTable"); // Declare variables for DataColumn and DataRow objects.

    DataColumn column; DataRow row;

    // Create new DataColumn, set DataType,// ColumnName and add to DataTable.column = newDataColumn();column.DataType = System.Type.GetType("System.Int32");column.ColumnName = "id";column.AutoIncrement = true;

  • 8/8/2019 ASP[1].NET 3.5

    25/29

    column.Unique = true;column.ReadOnly = true;

    // Add the Column to the DataColumnCollection.table.Columns.Add(column);

    // Create second column.column = newDataColumn();column.DataType = System.Type.GetType("System.String");column.ColumnName = "ParentItem";column.AutoIncrement = false;column.Caption = "ParentItem";column.Unique = false;column.ReadOnly = false;

    // Add the column to the table.table.Columns.Add(column);

    // Make the ID column the primary key column. DataColumn[] PrimaryKeyColumns = newDataColumn[1];

    PrimaryKeyColumns[0] = table.Columns["id"];

    table.PrimaryKey = PrimaryKeyColumns;

    // Instantiate the DataSet variable.dataSet = newDataSet();

    // Add the new DataTable to the DataSet.dataSet.Tables.Add(table);

    // Create three new DataRow objects and add// them to the DataTable

    for (int i = 0; i

  • 8/8/2019 ASP[1].NET 3.5

    26/29

    table.Columns.Add(column);

    // Create second column.column = newDataColumn();column.DataType = System.Type.GetType("System.String");

    column.ColumnName = "ChildItem";column.AutoIncrement = false;column.Caption = "ChildItem";column.ReadOnly = false;column.Unique = false;table.Columns.Add(column);

    // Create third column.column = newDataColumn();column.DataType = System.Type.GetType("System.Int32");column.ColumnName = "ParentID";column.AutoIncrement = false;column.Caption = "ParentID";column.ReadOnly = false;

    column.Unique = false;table.Columns.Add(column);

    dataSet.Tables.Add(table);

    // Create three sets of DataRow objects,// five rows each, and add to DataTable.

    for (int i = 0; i

  • 8/8/2019 ASP[1].NET 3.5

    27/29

    // DataRelation requires two DataColumn// (parent and child) and a name.

    DataColumn parentColumn = dataSet.Tables["ParentTable"].Columns["id"]; DataColumn childColumn =dataSet.Tables["ChildTable"].Columns["ParentID"];

    DataRelation relation = newDataRelation("parent2Child", parentColumn,childColumn);dataSet.Tables["ChildTable"].ParentRelations.Add(relation);

    }

    privatevoid BindToDataGrid(){

    // Instruct the DataGrid to bind to the DataSet, with the// ParentTable as the topmost DataTable.

    //GridView1.SetDataBinding(dataSet, "ParentTable");GridView1.DataSource = dataSet;GridView1.DataBind();

    }

    }

    DataSet

    The DataSet, which is an in-memory cache of data retrieved from a data source, is a majorcomponent of the ADO.NET architecture. The DataSet consists of a collection of DataTableobjects that you can relate to each other with DataRelation objects.

    Creating a DataSet

    You create an instance of a DataSet by calling the DataSet constructor. Optionally specify aname argument. If you do not specify a name for the DataSet, the name is set to "NewDataSet".

    DataSet customerOrders = newDataSet("CustomerOrders");

    Adding a DataTable to a DataSet

    ADO.NET enables you to create DataTable objects and add them to an existing DataSet. You canset constraint information for a DataTable by using the PrimaryKey and Unique properties.

    DataSet customerOrders = newDataSet("CustomerOrders");

    DataTable ordersTable = customerOrders.Tables.Add("Orders");

    DataColumn pkOrderID =ordersTable.Columns.Add("OrderID", typeof(Int32));

    ordersTable.Columns.Add("OrderQuantity", typeof(Int32));ordersTable.Columns.Add("CompanyName", typeof(string));

    ordersTable.PrimaryKey = newDataColumn[] { pkOrderID };

  • 8/8/2019 ASP[1].NET 3.5

    28/29

    Creating and Using DataViews

    A DataView enables you to create different views of the data stored in a DataTable, a capabilitythat is often used in data-binding applications. Using a DataView, you can expose the data in a

    table with different sort orders, and you can filter the data by row state or based on a filterexpression.

    Creating a DataView

    There are two ways to create aDataView. You can use the DataView constructor, or you cancreate a reference to theDefaultView property of the DataTable. The following code exampledemonstrates how to create a DataView using the DataView constructor. A RowFilter, Sortcolumn, and DataViewRowState are supplied along with the DataTable.

    DataView custDV = newDataView(custDS.Tables["Customers"],

    "Country = 'USA'", "ContactName", DataViewRowState.CurrentRows);

    The following code example demonstrates how to obtain a reference to the default DataView ofa DataTable using the DefaultView property of the table.

    DataView custDV = custDS.Tables["Customers"].DefaultView;

    Sorting and Filtering Data Using a DataView

    The DataViewprovides several ways of sorting and filtering data in a DataTable:

    You can use the Sort property to specify single or multiple column sort orders and includeASC (ascending) and DESC (descending) parameters.

    Deleting DataRows (ADO.NET)

    http://msdn.microsoft.com/en-us/library/03c7a3zb.aspx

    There are two methods you can use to delete a DataRow object from aDataTable object: theRemove method of the DataRowCollectionobject, and theDelete method of the DataRow

    object. Whereas the Remove method deletes a DataRow from the DataRowCollection, theDelete method only marks the row for deletion. The actual removal occurs when the applicationcalls the AcceptChanges method. By using Delete, you can programmatically check which rowsare marked for deletion before actually removing them. When a row is marked for deletion, itsRowState property is set to Deleted.

    http://msdn.microsoft.com/en-us/library/system.data.dataview(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataview(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataview(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.datatable.defaultview(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.datatable.defaultview(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.datatable(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataview(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataview(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.datatable(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataview.sort(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.datarow.aspxhttp://msdn.microsoft.com/en-us/library/system.data.datatable.aspxhttp://msdn.microsoft.com/en-us/library/system.data.datatable.aspxhttp://msdn.microsoft.com/en-us/library/system.data.datarowcollection.aspxhttp://msdn.microsoft.com/en-us/library/system.data.datarowcollection.aspxhttp://msdn.microsoft.com/en-us/library/system.data.datarow.delete.aspxhttp://msdn.microsoft.com/en-us/library/system.data.datarow.delete.aspxhttp://msdn.microsoft.com/en-us/library/system.data.datarow.rowstate.aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataview(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.datatable.defaultview(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.datatable(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataview(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.datatable(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataview.sort(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/system.data.datarow.aspxhttp://msdn.microsoft.com/en-us/library/system.data.datatable.aspxhttp://msdn.microsoft.com/en-us/library/system.data.datarowcollection.aspxhttp://msdn.microsoft.com/en-us/library/system.data.datarow.delete.aspxhttp://msdn.microsoft.com/en-us/library/system.data.datarow.rowstate.aspx
  • 8/8/2019 ASP[1].NET 3.5

    29/29

    When using a DataSet orDataTable in conjunction with a DataAdapter and a relational datasource, use the Delete method of the DataRow to remove the row. The Delete method marks therow as Deleted in the DataSet orDataTable but does not remove it. Instead, when theDataAdapter encounters a row marked as Deleted, it executes its DeleteCommand method to

    delete the row at the data source. The row can then be permanently removed using theAcceptChanges method. If you use Remove to delete the row, the row is removed entirely fromthe table, but the DataAdapter will not delete the row at the data source.

    The Remove method of the DataRowCollection takes a DataRow as an argument and removesit from the collection, as shown in the following example.

    workTable.Rows.Remove(workRow);

    In contrast, the following example demonstrates how to call the Delete methodon a DataRow to change its RowState to Deleted.

    workRow.Delete();

    If a row is marked for deletion and you call the AcceptChanges method of the DataTableobject, the row is removed from the DataTable. In contrast, if you call RejectChanges, theRowState of the row reverts to what it was before being marked as Deleted.

    http://msdn.microsoft.com/en-us/library/system.data.dataset.aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataset.aspx