Вы находитесь на странице: 1из 29

ASP.

NET State Management

HTTP is a stateless protocol. After every web request, the client disconnects from the
server, 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. You
choose the right option depending on the data you need to store, the length of time you want to
store it, the scope of your data (whether it's limited to individual or shared across multiple
requests), and additional security and performance considerations.

1. View State
2. Query String
3. Custom Cookies
4. Session State
5. Application State
6. 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"];
URL Encoding
Its allow special characters [e.g. #, $, etc.] to use Query String. HttpServerUtility class encode or
decode 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 = new HttpCookie("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 if
you are using the default in-process state service.
Storage location: Server memory (by default), or a dedicated database, depending on
the mode you choose.
Lifetime: Times out after a predefined period (usually 20 minutes but can be altered
globally 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"];
It allows information to be stored in one page and accessed in another and it supports any type of
objects. 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 some
extra 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 proprietary
algorithm to generate this value [Session Id]. This ID is the only piece of information that is
transmitted 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 accessed
in code. This process takes place automatically.

Class: System.Web.SessionState.HttpSessionState
Session 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 ways
1. Using cookies: In this case, the session ID is transmitted in a special cookie [named
ASP.NET_SessionId], which ASP.NET creates automatically when the session collection is
used. 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 support
cookies.

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 URLs
IsNewSession: Identifies whether this session was just created for the current request.
Mode: Provides an enumerated value that explains how ASP.NET stores session state
information. 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 = 10k20j39did9o9930d
The following are the collections of the created Session.
Session["a"]
Session["b"]
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.

<configuration>
<system.web>
<sessionState mode="StateServer/SQLServer/Off/Custom/InProc"
stateConnectionString ="tcpip=127.0.0.1:42424"
stateNetworkTimeout ="10"
sqlConnectionString ="data source=127.0.0.1;
Integrated Security=SSPI"
sqlCommandTimeout ="30"
allowCustomSqlDatabase ="false"
useHostingIdentity ="true"
cookieless ="UseCookies"
cookieName ="ASP.NET_SessionId"
regenerateExpiredSessionId ="false"
timeout ="20"
customProvider ="" />
</system.web>
</configuration>

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 application
domain.
StateServer: Use a separate Windows service for state management.
SQLServer: Use a SQL Server database to store session information. as identified by the
sqlConnectionString attribute.

5. Application State

Allowed data types: All .NET data


Storage location: Server memory
Lifetime: 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: Permanent
Scope: The whole ASP.NET application. May also be accessed by other
applications.
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 set
Scope: 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 useful
cached 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 it
is 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 as
data 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, executing
commands, and retrieving results. Those results are either processed directly, or placed in an
ADO.NET DataSet object in order to be exposed to the user in an ad-hoc manner, combined
with data from multiple sources, or remoted between tiers. The ADO.NET DataSet object can
also be used independently of a .NET Framework data provider to manage data local to the
application 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, reference
both System.Data.dll and System.Xml.dll.

ADO.NET Architecture

ADO.NET uses a multilayered architecture.


a) Connected Layer
b) 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 .NET
Framework 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 it
can be used with multiple and differing data sources, used with XML data, or used to manage
data local to the application. The DataSet contains a collection of one or more DataTable
objects made up of rows and columns of data, as well as primary key, foreign key, constraint, and
relation information about the data in the DataTable objects.

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


Using ADO.NET Disconnected Classes
Disconnected data access classes: DataTable and DataSet
DataTable Object

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

class Program
{
private DataTable getDataTable()
{
//Create the DataTable named "employee".
DataTable employee = new DataTable("Employee");

//Add the DataColumn using all properties


DataColumn eid = new DataColumn("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 = new DataColumn("FirstName");
firstName.MaxLength = 35;
firstName.AllowDBNull = false;
employee.Columns.Add(firstName);

DataColumn lastName = new DataColumn("LastName");


lastName.AllowDBNull = false;
employee.Columns.Add(lastName);

//Add the decimal DataColumn using defaults


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

//Derived column using Expression


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

//Set the Primary key


employee.PrimaryKey = new DataColumn[] {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;
}

static void Main(string[] args)


{
Program p = new Program();
p.getDataTable();
Console.ReadLine();
}

Using the DataTable with XML Data


static void Main(string[] args)
{
DataSet ds = new DataSet();
Program p = new Program();
ds.Tables.Add(p.getDataTable());
ds.WriteXml("E:\\Prakash\\CSharp Windows
Application\\InterfaceExample\\InterfaceExample\\XMLFile1.xml");
Console.ReadLine();

DataView
static void Main(string[] args)
{
DataSet ds = new DataSet();
Program p = new Program();
ds.Tables.Add(p.getDataTable());
//Sort and Display
DataView view = new DataView(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();

}
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. The
Command object enables access to database commands to return data, modify data, run stored
procedures, and send or retrieve parameter information. The DataReader provides a high-
performance stream of data from the data source. Finally, the DataAdapter provides the bridge
between the DataSet object and the data source. The DataAdapter uses Command objects to
execute SQL commands at the data source to both load the DataSet with data, and reconcile
changes 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, and
retrieving results. Those results are either processed directly, or placed in an ADO.NET DataSet
in order to be exposed to the user in an ad-hoc manner, combined with data from multiple
sources, or remoted between tiers. The .NET Framework data provider is designed to be
lightweight, creating a minimal layer between the data source and your code, increasing
performance 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 data
source.
Command Executes a command against a data source.
Exposes Parameters and can execute within the
scope of a Transaction from a Connection.
DataReader Reads a forward-only, read-only stream of data
from a data source.
DataAdapter Populates a DataSet and resolves updates with
the 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
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. The
following table discusses the advantages and limitations of each .NET Framework data provider.

Provider Notes
.NET Framework Data Recommended for middle-tier applications using Microsoft SQL Server
Provider for SQL 7.0 or later.
Server
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 the
OLE DB Provider for SQL Server with the .NET Framework Data
Provider for OLE DB.
.NET Framework Data Recommended for middle-tier applications using Microsoft SQL Server
Provider for OLE DB 6.5 or earlier, or any OLE DB provider that supports the OLE DB
interfaces listed in OLE DB Interfaces Used by the .NET Framework
Data 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 Access


databases. Use of a Microsoft Access database for a middle-tier
application is not recommended.
.NET Framework Data Recommended for middle-tier applications using ODBC data sources.
Provider for ODBC
Recommended for single-tier applications using ODBC data sources.

Note The .NET Framework Data Provider for ODBC is


not included in the .NET Framework version 1.0. If you
require the .NET Framework Data Provider for ODBC
and are using the .NET Framework version 1.0, you can
download the .NET Framework Data Provider for ODBC
at http://msdn.microsoft.com/downloads. The namespace
for the downloaded .NET Framework Data Provider for
ODBC is Microsoft.Data.Odbc.
.NET Framework Data Recommended for middle-tier applications using Oracle data sources.
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 in
the System.Data.OracleClient namespace and are contained in the
System.Data.OracleClient.dll assembly. You need to reference both
the System.Data.dll and the System.Data.OracleClient.dll when
compiling 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 Framework
Data Provider for ODBC, the .NET Framework Data Provider for OLEDB, the .NET Framework
Data Provider for Oracle, and the .NET Framework Data Provider for SQL Server. The classes in
System.Data.Common are intended to give developers a way to write ADO.NET code that will
work against all .NET Framework data providers.

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

BASE CLASS SQLCLIENT CLASSES GENERIC INTERFACE


DbConnection SqlConnection IDBConnection
DbCommand SalCommand IDBCommand
DbDataReader SqlDataReader IDataReader/IDataRecord
DbTransaction SqlTransaction IDbTransaction
DbParameter SqlParameter IDBDataParameter
DbDataAdapter SqlDataAdapter IDbDataAdapter

appSettings Element

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

<configuration>
<appSettings>
<add key="Application Name" value="MyApplication" />
</appSettings>
</configuration>
<appSettings file="">
<settings>
<clear />
</settings>
</appSettings>
<appSettings>
<add key="DocumentPath" value="~/DocumentPath/"/>
<add key="FileType" value=".doc,.jpg,.bmp,.gif,.pdf"/>
<!-- File Limit 4 MB ( 4096 ) -->
<add key="FileSizeLimit" value="4096"/>
<add key="debugMode" value="0"/>
<add key="LogFilePath"
value="D:\backup\Projects\MFDA.S.0007.MOBLD\Source
Code\MOBLD\MOWebSite\Log\mobld.log"/>
<add key="ServiceUser" value="mfdawebadmin"/>
<add key="ServicePwd" value="~password"/>
<add key="HelpFile" value="~/Help/MFDA_help.pdf"/>
<add key="MOWebService.moservice"
value="http://localhost:2914/MOService/MOService.asmx"/>
<add key="UMWebService.umservice"
value="http://localhost:2918/UMService/UMService.asmx"/>
<add key="FCKeditor:UserFilesPath" value="~/UserFiles/" />
</appSettings>

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

ConnectionStrings Element

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


applications and features.

<connectionStrings >
<add /> Adds a connection string as a name/value pair to the collection of
connection strings.
<clear /> Removes all references to inherited connection strings, allowing
only the connection strings that are added by the current add element.
<remove /> Removes a reference to an inherited connection string from the
collection of connections strings.
</connectionStrings>

<connectionStrings>
<add name="MOBLDUM" connectionString="Data Source=svr2k02;Initial
Catalog=MFDAUM;Persist Security Info=True;User ID=sa;PWD=password;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
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 data


source.

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 rows
affected. 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 the
query. Additional columns or rows are ignored.

3. SqlCommand.ExecuteReader Method
Executes a SELECT query and returns a DataReader object that wraps a read-only, forward-only
cursor.

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)


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-transaction
state.

Transactions in ADO.NET are used when you want to bind multiple tasks together so that
they execute as a single unit of work.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"


DataKeyNames="Sl,status" AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="2"
AllowSorting="True" OnSorting="GridView1_Sorting">
<Columns>
<asp:BoundField DataField="Sl" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="Address"
HeaderText="Address" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" Checked='<%#
Eval("status") %>' runat="server" Enabled="true">
</asp:CheckBox>
<asp:HiddenField ID="id" Value='<%# Bind("Sl")
%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>

</Columns>

</asp:GridView>

Update Checked Status

WebService wsObj = new WebService();


protected void Page_Load(object sender, EventArgs e)
{
Label2.Text = "Page created at: " + DateTime.Now.ToLongTimeString();
if (!Page.IsPostBack)
{
DataSet ds = new DataSet();
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();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
//lb.Text = "Panel refreshed at: " + DateTime.Now.ToLongTimeString();
Label1.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString();
DataSet ds = new DataSet();
ds = wsObj.WSGetInfo();
GridView1.DataSource = ds;
GridView1.DataBind();

}
protected void 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
// 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);
else
wsObj.WSUpdateStatus(0, val);
}
}
protected void 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();
}

public DataView bindGrid()


{
DataSet ds = new DataSet();
DataView dv = new DataView();
ds = wsObj.WSGetInfo();
if (ViewState["SortExp"] != null)
{
dv = new DataView(ds.Tables[0]);
dv.Sort = ViewState["SortExp"].ToString();
}
else
{
dv = ds.Tables[0].DefaultView;
}
return dv;
}
protected void GridView1_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{

GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = bindGrid();
GridView1.DataBind();
}
protected void 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();
}
}

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="EXPORT AS XML" /><br />
<br />
<asp:GridView ID="GridView1" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
AllowPaging="True" AllowSorting="True"
OnPageIndexChanging="GridView1_PageIndexChanging"
OnSorting="GridView1_Sorting" PageSize="3"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True"
ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White"
HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True"
ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True"
ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Sl" HeaderText="Sl"
SortExpression="Sl" />
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="Address" HeaderText="Address"
/>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:CheckBox ID="chkStatus" runat="server"
Checked='<%# Eval("status") %>'/>
<asp:HiddenField ID="chkHidden" runat="server"
Value='<%# Bind("Sl")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Items">
<ItemTemplate>
<asp:DropDownList ID="ddlItem" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>

&nbsp;&nbsp;<br />
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="~/Files/Indexdotnet.pdf">Link</asp:HyperLink><br />
<br />
</div>
</form>
</body>
</html>
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;

public partial class _Default : System.Web.UI.Page


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

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
//GridViewRow row = GridView1.
DataBinder();
}
}

protected void Button1_Click(object sender, EventArgs e)


{
int i;
DataSet ds = new DataSet();
DataTable dt = new DataTable("TestTable");
dt.Columns.Add(new DataColumn("Sl",
System.Type.GetType("System.Int32")));
dt.Columns.Add(new DataColumn("Name",
System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Address",
System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("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);
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);
}
}

protected void GridView1_PageIndexChanging(object sender,


GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
DataBinder();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
Response.Write(e.SortDirection.ToString() + " ========== " +
e.SortExpression.ToString());

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs


e)
{
GridView1.EditIndex = e.NewEditIndex;
}
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
//TextBox txtName = e.Keys[e.]
}
protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
{

}
protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{

}
protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
}

public void DataBinder()


{
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;

public partial class DataSetRelation : System.Web.UI.Page


{
DataSet dataSet;
protected void Page_Load(object sender, EventArgs e)
{
//http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx

MakeDataTables();
}

private void MakeDataTables()


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

private void MakeParentTable()


{

// Create a new DataTable.


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

// Create new DataColumn, set DataType,


// ColumnName and add to DataTable.
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
column.AutoIncrement = true;
column.Unique = true;
column.ReadOnly = true;
// Add the Column to the DataColumnCollection.
table.Columns.Add(column);

// Create second column.


column = new DataColumn();
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 = new DataColumn[1];
PrimaryKeyColumns[0] = table.Columns["id"];
table.PrimaryKey = PrimaryKeyColumns;

// Instantiate the DataSet variable.


dataSet = new DataSet();
// 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 <= 2; i++)
{
row = table.NewRow();
row["id"] = i;
row["ParentItem"] = "ParentItem " + i;
table.Rows.Add(row);
}
}

private void MakeChildTable()


{
// Create a new DataTable.
DataTable table = new DataTable("childTable");
DataColumn column;
DataRow row;

// Create first column and add to the DataTable.


column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "ChildID";
column.AutoIncrement = true;
column.Caption = "ID";
column.ReadOnly = true;
column.Unique = true;

// Add the column to the DataColumnCollection.


table.Columns.Add(column);

// Create second column.


column = new DataColumn();
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 = new DataColumn();
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 <= 4; i++)
{
row = table.NewRow();
row["childID"] = i;
row["ChildItem"] = "Item " + i;
row["ParentID"] = 0;
table.Rows.Add(row);
}
for (int i = 0; i <= 4; i++)
{
row = table.NewRow();
row["childID"] = i + 5;
row["ChildItem"] = "Item " + i;
row["ParentID"] = 1;
table.Rows.Add(row);
}
for (int i = 0; i <= 4; i++)
{
row = table.NewRow();
row["childID"] = i + 10;
row["ChildItem"] = "Item " + i;
row["ParentID"] = 2;
table.Rows.Add(row);
}
}

private void MakeDataRelation()


{
// 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 = new DataRelation("parent2Child", parentColumn,
childColumn);
dataSet.Tables["ChildTable"].ParentRelations.Add(relation);
}

private void 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 major
component of the ADO.NET architecture. The DataSet consists of a collection of DataTable
objects 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 a
name argument. If you do not specify a name for the DataSet, the name is set to "NewDataSet".

DataSet customerOrders = new DataSet("CustomerOrders");

Adding a DataTable to a DataSet

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

DataSet customerOrders = new DataSet("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 = new DataColumn[] { pkOrderID };


Creating and Using DataViews

A DataView enables you to create different views of the data stored in a DataTable, a capability
that 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 filter
expression.

Creating a DataView

There are two ways to create a DataView. You can use the DataView constructor, or you can
create a reference to the DefaultView property of the DataTable. The following code example
demonstrates how to create a DataView using the DataView constructor. A RowFilter, Sort
column, and DataViewRowState are supplied along with the DataTable.

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


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

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

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

Sorting and Filtering Data Using a DataView

The DataView provides 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 include
ASC (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 a DataTable object: the
Remove method of the DataRowCollection object, and the Delete method of the DataRow
object. Whereas the Remove method deletes a DataRow from the DataRowCollection, the
Delete method only marks the row for deletion. The actual removal occurs when the application
calls the AcceptChanges method. By using Delete, you can programmatically check which rows
are marked for deletion before actually removing them. When a row is marked for deletion, its
RowState property is set to Deleted.
When using a DataSet or DataTable in conjunction with a DataAdapter and a relational data
source, use the Delete method of the DataRow to remove the row. The Delete method marks the
row as Deleted in the DataSet or DataTable but does not remove it. Instead, when the
DataAdapter 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 the
AcceptChanges method. If you use Remove to delete the row, the row is removed entirely from
the 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 removes
it from the collection, as shown in the following example.

workTable.Rows.Remove(workRow);

In contrast, the following example demonstrates how to call the Delete method
on 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 DataTable
object, the row is removed from the DataTable. In contrast, if you call RejectChanges, the
RowState of the row reverts to what it was before being marked as Deleted.

Вам также может понравиться