Académique Documents
Professionnel Documents
Culture Documents
(1)
What is XML?
XML describes data as a combination of
markup language and content that is
analogous to the way HTML describes a
webpage.
XML is a markup language for text. It is
extensible,platform independent,supports
internationalization and localization and it is
fully Unicode compliant.
XML serves as the universal form for
structured documents and the data on the web.
ww
n
i
.
e
b
u
et
.cs
EXAMPLE
Person.xml
<?xml version=1.0?>
<!DOCTYPE person SYSTEM
http://www.example.org/dtds/person.dtd>
<person>
<name>
<first-name>Alan</first-name>
<last-name>Turing</last-name>
</name>
<profession>Computer Scientist</profession>
<profession>mathematician</profession>
</person>
File render.xsl
<?xml version=1.0?>
<xsl:stylesheet version=1.0
Xmlns :xsl =
http://www.w3.org/1999/xsl/Transform>
<xsl: template match = />
<html> <body>
<h1> <xsl : value-of-select =
message/></h1>
</body? </html?
</xsl:template>
</xsl:stylesheet>
(3)
What is XPath?
(2)
What is XSLT?
XSLT
XSLT stands for Extensible style sheet
Language transformations.
An XSLT is used by an XML enabled browser
to transform an XML document into a HTML
document so the contents of the XML
document can be displayed in a browser.
www.csetube.in
2
1.
2.
3.
4.
Operating System
/ = the root directory
/users/dave/foo = the file named foo in dave in
users
Foo = the file named foo in the current
directory
. = the current directory
.. = the parent directory
What is the role of XML in .NET?
Extensible markup Language (XML)
plays a key role in the .NET universe.
Web page behaviour configuration files
are deployed in XML.
Objects are stored or streamed across
the Internet by serializing them into an
XML representation
Web Services intercommunication is
based onXML
XML describes data as a combination
of markup language and content that is
analogous to the way HTMl describes
a web page.
XML is flexible
We can represent flat,relational or
hierarchical data
XML design goals
It should be human-legible and
reasonably clear it is represented in a
text only format
Major Advantage of XML
It is platform independent which ihas
made it defacto standard for transmitting data
over the Internet.
(6)
XmlSerializer Class
XML Serialization
(4)
n
i
.
e
b
u
et
(5)
What ability is provided by XML
functional literacy ?
cs
.
w
w
w
www.csetube.in
3
either case, the classes are annotated with
custom attributes to instruct the XmlSerializer
how to map between the XML schema system
and the common language runtime. At
runtime, instances of the classes can be
serialized into XML documents that follow the
given schema. Likewise, these XML
documents can be deserialized into runtime
objects. Note that the XML schema is
optional, and not required at design time or
runtime.
<MyClass>
<MyObjectProperty>
<ObjectName>My String</ObjectName>
</MyObjectProperty>
</MyClass>
n
i
.
e
b
u
et
cs
.
w
w
w
}
class Program
{
static void Main()
{
// create new object and populate test data
myTestClass test = new myTestClass();
test.myArray[0] = "qwerty";
test.myArray[1] = "asdfgh";
test.myArray[2] = "zxcvbn";
test.myArray[3] = "123456";
// these lines do the actual serialization
XmlSerializer mySerializer = new
XmlSerializer(typeof(myTestClass));
StreamWriter myWriter = new
StreamWriter("c:/myTestClass.xml");
mySerializer.Serialize(myWriter, test);
myWriter.Close();
}
}
www.csetube.in
4
In this example the first line creates an
XmlSerializer using the typeof method to
create a serialize specific to the myTestClass
class. We then create a StreamWriter pointing
to an xml file on the C drive. Finally, we call
the Serialize method of the Serializer passing
in the parameters for the writer and the object
itself. Finally we close the writer stream.
test =
(myTestClass)mySerializer.Deserialize(myFil
eStream);
}
(7)
What are the steps involved in
transforming a C# object to an xml
document?
b
u
et
.cs
</myArray>
</myTestClass>
w
w
w
Deserialization
Deserialization is the reverse process. We will
load in an xml document, pass the data to the
deserializer and produce an instance of the
class populated with the data.
n
i
.
e
<films>
<movies>
<movie_ID>5</movie_ID>
<movie_Title>Citizen Kane
</movie_Title>
<movie_Year>1941</movie_Year>
<movie_DirectorID>Orson
Welles</movie_DirectorID>
<bestPicture>Y</bestPicture>
<AFIRank>1</AFIRank>
</movies>
www.csetube.in
5
<movies>
bestPicture = pic;
<movie_ID>6</movie_ID>
rank = movierank;
<movie_Title>Casablanca
</movie_Title>
movie_Title = title;
movie_Year = yr;
<movie_Year>1942</movie_Year>
<movie_Director>Michael
Curtiz</movie_Director>
<bestPicture>Y</bestPicture>
<AFIRank>1</AFIRank>
</movies>
</films>
using System.Xml;
w
w
w
b
u
et
.cs
using System.Xml.Serialization;
// other code here ...
n
i
.
e
{
get { return mDirector; }
{
movieID = ID;
movie_Director = dir;
www.csetube.in
6
}
XmlRootAttribute();
xRoot.ElementName = "films";
xRoot.Namespace =
"http://www.corecsharp.net";
xRoot.IsNullable = true;
// Specify that an array of movies
types is to be serialized
XmlSerializer xSerial = new
XmlSerializer(typeof(movies[]),
[XmlElement("AFIRank")]
public int rank
{
get { return mAFIRank; }
set { mAFIRank = value; }
xRoot);
string
filename=@"c:\oscarwinners.xml";
// (3) Stream to write XML into
TextWriter writer = new
StreamWriter(filename);
xSerial.Serialize(writer,films);
}
private int mID;
private string mTitle;
private int mYear;
(8)
What is XML Schema? How it is
defined?
XML schema is essentially a
template that defines in detail what is
permitted in an associated XML document. Its
role is similar to that of the BNF (BackusNaur Form) notation that defines a language's
syntax for a compiler.
n
i
.
e
cs
.
w
b
u
et
w
w
(12)
shown in Listing 10-3.
www.csetube.in
7
implements validation as a read and check
process. As a class iterates through each node
in an XML tree, the node is validated . Listing
10-4 illustrates how the
XmlValidatingReader class performs this
operation.
xmlns=""
xmlns:xs=http://www.w3.org/2001/XML
Schema
xmlns:msdata="urn:schemasmicrosoft-com:xml-msdata">
<xs:element name="films"
msdata:IsDataSet="true">
<xs:complexType>
<xs:choice minOccurs="0"
maxOccurs="unbounded">
<xs:element name="movies">
<xs:complexType>
<xs:sequence>
<xs:element
name="movie_ID" type="xs:int"
minOccurs="0"
/>
<xs:element
name="movie_Title" type="xs:string"
minOccurs="0"
/>
<xs:element
name="movie_Year" type="xs:int"
minOccurs="0"
/>
<xs:element
name="movie_Director"
type="xs:string"
minOccurs="0"
/>
<xs:element
name="bestPicture" type="xs:string"
minOccurs="0"
/>
<xs:element
name="AFIRank" type="xs:int"
minOccurs="0"
/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
b
u
et
cs
.
w
w
w
n
i
.
e
www.csetube.in
8
return true;
n
i
.
e
b
u
et
.cs
w
w
w
www.csetube.in
9
<td
align="center"><xsl:value-of
select=
"AFIRank" /></td>
<td><xsl:value-of
select="movie_Director" /></td>
</tr>
</xsl:for-each>
</Table>
</HTML>
</xsl:template>
</xsl:stylesheet>
XmlTextWriter("c:\movies.htm",Encodin
g.UTF8);
XslTransform xslt = new
XslTransform();
XPathDocument xpd = new
xslt.Load("movies.xsl");
b
u
et
cs
.
w
w
w
n
i
.
e
XPathDocument("c:\oscarwinners.xml");
xslt.Transform(xpd, null,
writer,null);
www.csetube.in
10
Listing 10-6. Using XmlReader to Read an XML
Document
XmlReader Class
XmlReader
n
i
.
e
b
u
et
cs
.
w
w
w
settings);
while (rdr.Read())
{
Format(rdr);
}
rdr.Close();
}
catch (Exception e)
{
Console.WriteLine ("Exception:
{0}", e.ToString());
}
}
private static void
Format(XmlTextReader reader)
{
//(3) Print Current node
properties
Console.Write( reader.NodeType+
"<" + reader.Name + ">" +
reader.Value);
Console.WriteLine();
}
. The statement
settings.ConformanceLevel
ConformanceLevel.Fragment;
www.csetube.in
11
EndElement<movie_Title>
...
(12)EndElement<films>
XmlReader
rdr
=
XmlReader.Create("c:\oscarsshort.xml,
settings);
XmlNodeReader Class
The file's content is read in a node at a time by
the XmlReader.Read method, which prints
the NodeType , Name , and Value of each
node.
Listing 10-7 shows the input file and a portion
of the generated output. Line numbers have
been added so that an input line and its
corresponding node information can be
compared.
n
i
.
e
b
u
et
cs
.
w
w
w
www.csetube.in
12
XmlReader reader =
XmlReader.Create(noderdr, settings);
while (reader.Read())
{
if(reader.NodeType==XmlNodeType.Eleme
nt){
if (reader.Name ==
"movie_Title")
{
reader.Read(); // next
node is text for title
Console.Write(reader.Value);
//
Movie Title
}
if (reader.Name ==
"movie_Year")
{
reader.Read(); // next
node is text for year
Console.WriteLine(reader.Value); //
year
}
}
}
}
//
n
i
.
e
b
u
et
cs
.
w
w
w
XmlDocument
www.csetube.in
13
w
w
n
i
.
e
b
u
et
cs
.
w
XPathNodeIterator iterator =
nav.Select(XPATHEXPRESSION);
XmlDocument
www.csetube.in
14
n
i
.
e
Recursive
descendant
operator (
// )
cs
.
w
b
u
et
w
w
Wildcard
operator (
* )
Current
operator (
. )
www.csetube.in
15
Operator Description
find any last_name child nodes:
.//last_name
Parent
operator (
.. )
Attribute
operator (
@ )
n
i
.
e
//movies//@time
Filter
operator (
[ ] )
b
u
et
cs
.
w
w
w
//directors[last_name='Scor
sese']
/movies/movie_Title
(Index is not 0
based.)
Union
operator (
| )
www.csetube.in
16
w
w
n
i
.
e
b
u
et
cs
.
w
string exp =
"/films/directors/last_name";
// Create method was added with .NET
2.0
XmlReader rdr =
XmlReader.Create("c:\directormovies.x
ml");
// Pass XmlReader to the constructor
xDoc = new XPathDocument(rdr);
XPathNavigator nav=
xDoc.CreateNavigator();
XPathNodeIterator iterator;
iterator = nav.Select(exp);
// List last name of each director
while (iterator.MoveNext())
Console.WriteLine(iterator.Current.Va
lue);
// Now, list only movies for Martin
Scorsese
string exp2 =
"//directors[last_name='Scorsese']/mo
vies/movie_Title";
iterator = nav.Select(exp2);
while (iterator.MoveNext())
Console.WriteLine(iterator.Current.Va
lue);
www.csetube.in
17
(20) Explain briefly how nodes are
added and removed from an XML
Document tree.
n
i
.
e
b
u
et
cs
.
w
w
w
xmlDoc.DocumentElement.SelectNodes(ex
p);
DataRow myRow;
foreach (XmlNode myNode in nodeList)
{
myRow =
xmlDoc.GetRowFromElement((XmlElement)
myNode);
if (myRow != null){
// Print Movie Title from a
DataRow
Console.WriteLine(myRow["movie_Title"
].ToString());
}
}
www.csetube.in
18
XmlDocument doc = new
XmlDocument();
doc.Load("c:\directormovies.xml");
// (1) Locate movie to remove
string exp =
"//directors[last_name='Scorsese']/
movies[movie_Title='Raging
Bull']";
XmlNode movieNode =
doc.SelectSingleNode(exp);
// (2) Delete node and child nodes
for movie
XmlNode directorNode =
movieNode.ParentNode;
directorNode.RemoveChild(movieNode);
// (3) Add new movie for this
director
//
First, get and save
director's ID
string directorID =
directorNode.SelectSingleNode("direct
or_id").InnerText;
// XmlElement is dervied from
XmlNode and adds members
XmlElement movieEl =
doc.CreateElement("movies");
directorNode.AppendChild(movieEl);
// (4) Add Movie Description
AppendChildElement(movieEl,
"movie_ID", "94");
AppendChildElement(movieEl,
"movie_Title", "Goodfellas");
AppendChildElement(movieEl,
"movie_Year", "1990");
AppendChildElement(movieEl,
"movie_DirectorID",
directorID);
// (5) Save updated XML Document
doc.Save("c:\directormovies2.xml");
}
// Create node and append to parent
public void
AppendChildElement(XmlNode parent,
string elName,
string
elValue)
{
XmlElement newEl =
n
i
.
e
b
u
et
cs
.
w
w
w
parent.OwnerDocument.CreateElement(el
Name);
newEl.InnerText = elValue;
parent.AppendChild(newEl);
}
www.csetube.in
19
developer, it presents a set of abstract classes
that define a common set of methods and
properties that can be used to access any data
source. The data source is treated as an
abstract entity, much like a drawing surface is
to the GDI+ classes. Figure 11-1 depicts this
concept.
n
i
.
e
b
u
et
cs
.
w
w
w
DbConnection
. Establishes a
connection to the data source.
DbCommand . Used to query or send a
command to the data source.
DbDataReader . Provides read-only
and forward-only access to the data
source.
DBDataAdapter . Serves as a channel
through which a DataSet connects to
a provider.
www.csetube.in
20
vendor's specific implementation within the
code.
Provider Factories
SqlCommand cmd
SqlCommand();
SqlDataReader dr
=
cmd.ExecuteReader();
DataTable tb =
DbProviderFactories.GetFactoryClasses
();
foreach (DataRow drow in tb.Rows )
{
StringBuilder sb = new
StringBuilder("");
for (int i=0; i<tb.Columns.Count;
i++)
{
sb.Append((i+1).ToString()).Append(dr
ow[i].ToString());
sb.Append("\n");
}
Console.WriteLine(sb.ToString());
}
n
i
.
e
b
u
et
cs
.
w
w
w
= new
www.csetube.in
21
factory.CreateCommand(); // Command
object
cmd.CommandText = "SELECT *
FROM movies WHERE movie_ID=8" ;
cmd.Connection = conn;
DbDataReader dr;
dr = cmd.ExecuteReader();
dr.Read();
MessageBox.Show((string)dr["movie_Tit
le"]);
conn.Close();
}
catch (DbException ex)
{ MessageBox.Show(ex.ToString());
}
catch (Exception ex)
{ MessageBox.Show(ex.ToString());
}
finally { conn.Close(); }
}
b
u
et
cs
.
w
w
w
n
i
.
e
www.csetube.in
22
//System.Data.SqlClient namespace is
required
// (1) Create Connection
SqlConnection conn = new
SqlConnection(connstr);
conn.Open();
// (2) Query string
string sql = "SELECT movie_Title FROM
movies ORDER BY
movie_Year";
// (3) Create Command object
SqlCommand cmd = new SqlCommand(sql,
conn);
DbDataReader rdr;
// (4) Create DataReader
rdr =
cmd.ExecuteReader(CommandBehavior.Clo
seConnection);
while (rdr.Read())
{
listBox1.Items.Add(rdr["movie_Title"]
); // Fill ListBox
}
rdr.Close(); // Always close
datareader
w
w
b
u
et
cs
.
w
n
i
.
e
www.csetube.in
23
Model?
(27) Explain how the connector class
implements the IDBConnection
interface.
Connection Classes
e
b
u
Property
t
e
cs
w
w
ConnectionString
Description
Gets or sets the string
used to connect to a
data source.
Property
Property
Database
Property
State
Method
Open Close
Opens a connection.
Rolls back any
pending operations
and closes the
connection
returning it to a
connection pool, if
one is used.
Method
BeginTransaction
Initiates a database
transaction.
Method
ChangeDatabase
.
w
.in
Category Name
www.csetube.in
24
database for an open
connection. The new
database name is
passed as string to the
method.
Method
CreateCommand
Creates a command
object to be
associated with
connection.
Server.MapPath("/data/movies.mdb");
Data Source="+path+";"
ODBC (DSN)
"DSN=movies;".
Connection String
User
Id=filmsadmin;Password=bogart;";
w
w
"server=MYSERVER;
password=bogart;Initial Catalog=films;"
SqlConnection
[2]
"server=MYSERVER;
Using Windows
authentication.
// Open connection
cs
.
w
Using SQL
Server
authentication.
b
u
et
conn.Open();
SqlConnection
n
i
.
e
database=films;
Trusted_Connection=yes"
OleDbConnection
"Provider=Microsoft.Jet.OLEDB.4.0;
Connects to a
Microsoft Access Data Source=c:\movies.mdb;"
database.
www.csetube.in
25
SqlConnectionStringBuilder sqlBldr =
new
SqlConnectionStringBuilder();
scb.DataSource
= "MYSERVER";
// Or scp["Data Source"] =
"MYSERVER";
sqlBldr.Password = "bogart";
sqlBldr.UserID
= "filmsadmin";
sqlBldr.InitialCatalog = "films";
SqlConnection conn = new
SqlConnection(sqlBldr.ConnectionStrin
g);
conn.Open();
string provider =
"System.Data.SqlClient";
n
i
.
e
DBProviderFactory factory =
cs
.
w
b
u
et
w
w
DbProviderFactories.GetFactory(provid
er);
DbCommand cmd
=
factory.CreateCommand();
cmd.CommandText = sql;
or command
// Query
cmd.Connection = conn;
Connection object
//
cmd.commandText = sql;
// Fill in parameter values in query
www.csetube.in
26
CommandText
Description
rdr = cmd.ExecuteReader(sql,
CommandBehavior.SingleResult);
cmd.CommandText = "DELETE
movies WHERE movie_ID=220";
int ct = cmd.ExecuteNonQuery();
ExecuteReader
.cs
w
w
w
SqlDataReader rdr=
cmd.ExecuteReader();
ExecuteScalar
cmd.CommandText="SELECT
COUNT(movie_title)
FROM movies";
int movieCt = (int)
cmd.ExecuteScalar();
ExecuteXmlReader
n
i
.
e
b
u
et
cmd.CommandText="SELECT *
FROM movies
WHERE movie_year > '1945';
SingleRow
dr=cmd.ExecuteReader(CommandB
ehavior.SchemaOnly);
string col1= dr.GetName(0);
// First column name
SequentialAccess . Permits data in
DataReader Object
As we have seen in several examples, a
DataReader exposes the rows and columns of
www.csetube.in
27
data returned as the result of executing a
query. Row access is defined by the
IDataReader interface that each DataReader
must implement; column access is defined by
the IDataRecord interface. We'll look at the
most important members defined by these
interfaces as well as some custom features
added by data providers.
Accessing Rows with DataReader
b
u
et
cs
.
w
w
w
n
i
.
e
{
while (rdr.Read())
{
MessageBox.Show(rdr.GetString(1));
}
readNext = rdr.NextResult(); //
Another resultset?
}
rdr.Close();
conn.Close();
www.csetube.in
28
Merge , and Clear
DataSet .
DataColumns
n
i
.
e
Method
b
u
et
Description
DataType
ww
.cs
Example: col1.DataType =
System.Type.GetType("System.String")
MaxLength
ReadOnly
Expression
Example: colTax.Expression =
"colSales * .085";
Caption
DataTable
DataTables
One step below the DataSet in the
disconnected model hierarchy is the
DataTable collection. This collection
DataTable
www.csetube.in
29
}
DataTable tb = new
DataTable("Order");
DataColumn dCol =
new DataColumn("ID",
Type.GetType("System.Int16"));
DataColumn[] col =
{tb.Columns["ID"]};
dCol.Unique = true;
// ID must be unique
for each data row
n
i
.
e
tb.PrimaryKey = col;
b
u
et
dCol.AllowDBNull = false;
DataRows
tb.Columns.Add(dCol);
dCol= new DataColumn("Price",
Type.GetType("System.Decimal"));
tb.Columns.Add(dCol);
.cs
w
w
w
dCol=new DataColumn("Quan",
Type.GetType("System.Int16"));
tb.Columns.Add(dCol);
row["Title"] = "Casablanca";
row["Price"] = 22.95;
tb.Columns.Add(dCol);
row["Quan"] = 2;
row["ID"] = 12001;
foreach
(DataColumn dc in tb.Columns)
// Create
tb.Rows.Add(row);
Rows collection
// Add row to
Console.WriteLine(tb.Rows[0]["Total"]
.ToString()); // 45.90
{
Console.WriteLine(dc.ColumnName);
Console.WriteLine(dc.DataType.ToStr
ing());
www.csetube.in
30
table. In order to do this, it keeps the status of
each row in the DataRow.RowState property.
This property is set to one of five
DataRowState enumeration values: Added ,
Deleted , Detached , Modifed , or
Unchanged . Let's extend the preceding
example to demonstrate how these values are
set:
Current
tb.Rows.Add(row);
// Added
Console.WriteLine("Current: {0}
Original: {1} ",
tb.AcceptChanges();
// ...Commit changes
r["Price",DataRowVersion.Current],
Console.Write(row.RowState);
// Unchanged
r["Price",DataRowVersion.Original]);
tb.Rows[0].Delete();
// Deleted
// output:
14.95
and Original :
DataRow r = tb.Rows[0];
r["Price"]= 14.95;
r.AcceptChanges();
r["Price"]= 16.95;
Current: 16.95
Original:
// Undo deletion
tb.RejectChanges();
// ...Roll back
b
u
et
Console.Write(tb.Rows[0].RowState);
// Unchanged
cs
.
w
DataRow myRow;
MyRow = tb.NewRow();
// Detached
w
w
n
i
.
e
www.csetube.in
31
DBDataReader rdr =
cmd.ExecuteReader(CommandBehavior.Clo
seConnection);
DataTable dt = new
DataTable("movies");
dt.PrimaryKey = col;
dt.Load(rdr);
// Load data and
schema into table
DataRow r = dt.Rows[0];
Get first row of data
//
//
Console.WriteLine(rdr.IsClosed);
True
//
b
u
et
cs
.
w
w
w
n
i
.
e
dt.Load(rdr,
LoadOption.UpdateCurrentValues );
// Updated value has been overwritten
Console.Write(dt.Rows[0]["movie_Title
"]); // Casablanca
//
Console.Write(dt.Rows[0]["movie_Title
"]); // Casablanca
www.csetube.in
32
// (1) The easiest: a query and
connection string as arguments
Table
SqlDataAdapter da = new
SqlDataAdapter(sql, connStr);
// Returns
SqlDataAdapter da = new
SqlDataAdapter();
SqlConnection conn = new
SqlConnection(connStr);
da.SelectCommand = new
SqlCommand(sql,conn);
n
i
.
e
b
u
et
SqlDataAdapter da = new
SqlDataAdapter(sql, conn);
cs
.
w
w
w
www.csetube.in
33
The DataAdapter has three properties
InsertCommand , DeleteCommand , and
UpdateCommand that are assigned the actual
SQL commands to perform the tasks that
correspond to the property name. These
commands are executed when the Upate
method of the DataAdapter is invoked. The
challenge lies in creating the SQL commands
that post the changes and assigning them to
the appropriate DataAdapter properties.
Fortunately, each data provider implements a
CommandBuilder class that can be used to
handle this task automatically.
w
w
n
i
.
e
b
u
et
cs
.
w
formatted stream.
drow["movie_Year"] = "1976";
dt.Rows.Add(drow);
dt.Rows[4].Delete();
// (4) Edit Column value
WriteXmlSchema
and GetXmlSchema
. Generates an XML Schema from the
DataSet schema.
ReadXmlSchema . Reads an XML
Schema file and creates a database
schema.
InferXmlSchema . Creates a DataSet
schema from XML data.
GetXml and GetXmlSchema , Returns
a string containing the XML
representation of the data or the XSD
schema for XML representation.
dt.Rows[5]["movie_Year"] = "1944";
www.csetube.in
34
(30) Explain how XML Data and
Schema files can be created using a
ADO.NET Dataset.
Using a DataSet to Create XML Data and
Schema Files
ds.WriteXml(("c:\oscarwinners.xml",
XmlWriteMode.WriteSchema);
*/
n
i
.
e
b
u
et
cs
.
w
w
w
www.csetube.in
35
DataSet ds = new DataSet();
ds.ReadXmlSchema("c:\oscars.xsd");
DataTable tb = ds.Tables[0];
// List Columns for table
string colList = tb.TableName +": ";
for (int i = 0; i < tb.Columns.Count;
i++)
{ colList += tb.Columns[i].Caption
+ " "; }
Console.WriteLine(colList);
/* output is:
movies: movie_ID movie_Title
movie_Year movie_DirectorID
bestpicture AFIRank
*/
w
w
n
i
.
e
b
u
et
cs
.
w
Parameters:
www.csetube.in
36
XMLfilename
mode
// Load XML data into dataset and create schema if one does
// not exist
DataSet ds = new DataSet();
ds.ReadXml("c:\oscarwinners.xml");
// Save source of data in dataset
ds.ExtendedProperties.Add("source", "c:\oscarwinners.xml");
ShowTable(ds.Tables[0]);
// Display each row in table
n
i
.
e
b
u
et
{
Schema Source
w
w
w
IgnoreSchema
InferSchema
ReadSchema
.cs
Ignores inline
schema, and
builds tables by
inference from
XML file. Error
occurs if DataSet
already contains
conflicting
schema.
If tables created
from inline
schema already
exist in DataSet ,
an exception is
thrown.
foreach(DataRow dr in t.Rows)
{
StringBuilder sb = new
StringBuilder("Table: ");
sb.Append(t.TableName).Append("\n");
foreach(DataColumn c in
t.Columns)
{
sb.Append(c.Caption).Append(": ");
sb.Append(dr[c.ColumnName].ToString()
).Append("\n");
}
Console.WriteLine(sb.ToString());
www.csetube.in
37
binding capabilities from the base
Control class, knowledge of its
properties and methods can be applied
to all controls. Many of the same
concepts apply to Web controls.
b
u
et
cs
.
w
w
w
n
i
.
e
www.csetube.in
38
Figure 12-1. Multiple controls bound to a single
data source
data
source
data
member
w
w
n
i
.
e
b
u
et
cs
.
w
www.csetube.in
39
through the array and display a different title
that corresponds to the current array item
selected. This scrolling is accomplished using
a binding manager , which is discussed
shortly.
ds = new DataSet("films");
string sql = "select * from movies
order by movie_Year";
da = new SqlDataAdapter(sql, conn);
da.Fill(ds,"movies");
//
create datatable "movies"
// Bind text property to movie_Year
column in movies table
txtYr.DataBindings.Add("Text",
ds,"movies.movie_Year");
b
u
et
.cs
w
w
w
"Tb_Background");
txtMovie.DataBindings.Add("Width",
tbList, "Tb_Width");
n
i
.
e
www.csetube.in
40
da.Fill(ds,"movies");
DataTable dt = ds.Tables[0];
// Minimum properties to bind
listbox to a DataTable
listBox1.DataSource = ds;
listBox1.DisplayMember =
"movies.movie_Title";
// Optional property that
assigns a value to each item row
listBox1.ValueMember =
"movies.movie_ID";
n
i
.
e
b
u
et
cs
.
w
w
w
txtStudio.DataBindings.Add("Text",
ds,"movies.studio");
txtYear.DataBindings.Add("Text",
ds,"movies.movie_Year");
www.csetube.in
41
dataGridView1.Columns[0].HeaderText =
"Movie Title";
Properties
dataGridView1.Columns[1].HeaderText =
"Year";
dataGridView1.Columns[1].Name = "Year";
ww
n
i
.
e
dataGridView1.Columns[0].Width = 150;
dataGridView1.Columns[1].Width = 40;
b
u
et
.cs
dataGridView1.Columns[2].HeaderText =
"Director";
dataGridView1.Columns[2].Width = 110;
// (2) Define style for data cells
(left,top,right,bottom)
style.SelectionBackColor = Color.LightBlue;
dataGridView1.DefaultCellStyle = style;
// (3) Define style for column headers
DataGridViewCellStyle styleHdr = new
DataGridViewCellStyle();
www.csetube.in
42
styleHdr.BackColor = Color.OldLace;
styleHdr.ForeColor = Color.Black;
dataGridView1.ColumnHeadersDefaultCellStyle
= styleHdr;
// (4) Define user capabilities
dataGridView1.AllowUserToAddRows
false;
=
DataBinding with a DataGridView
dataGridView1.AllowUserToOrderColumns =
false;
dataGridView1.AllowUserToDeleteRows =
false;
n
i
.
e
b
u
et
dataGridView1.AutoGenerateColumns = false;
dataGridView1.Rows.Add(row1);
.cs
ww
dataGridView1.Rows.Add(row2);
object[] row3 = {"On the
Waterfront","1954","Elia Kazan"};
dataGridView1.Rows.Add(row3);
dataGridView1.DataSource = ds;
// Dataset
dataGridView1.DataMember = "movies";
// Table in dataset
// Tie the columns in the grid to column names
in the data table
dataGridView1.Columns[0].DataPropertyName = "Title";
dataGridView1.Columns[1].DataPropertyName = "Year";
dataGridView1.Rows.Add(row4);
dataGridView1.Columns[2].DataPropertyName = "director";
}
The DataGridView supports two-way data binding for
Constructing a DataGridView
ADO.NET data sources: Changes made to the grid are reflected in
the underlying table, and changes made to the table are reflected
Listing 12-6 shows how to define columns for a DataGridView ,
in the grid.
set properties to define its appearance and behavior, and add
For example, this code responds to a button click by adding a new
rows of data. (We'll see in the succeeding example how to use
row to the grid's data source. The addition is immediately reflected
the more common approach of loading data from a database.)
in the control. However, if we try to add a row directly to the
www.csetube.in
43
Description
User
Indicates whether
functi AllowUserToAddR a user may
ows
onalit
add/delete rows.
y
AllowUserToDele Default: true .
teRows
{
// Adding to underlying table is okay
r[0] = "TAXI";
AllowUserToOrde
rColumns
Indicates whether
user can
rearrange
columns.
ColumnHeadersHe
ightResizable
Indicates whether
the user can
change the height
of the column
headers. Default:
TRue .
r[1] = "1976";
r[2] = "Martin Scorsese";
dt.Rows.Add(r);
n
i
.
e
b
u
et
DataRow r = dt.NewRow();
cs
.
w
DataGridView1.Rows.Add(row4); // Fails!
}
w
w
MultiSelect
Indicates whether
user may select
one or more rows
at a time.
SelectionMode
Indicates the
cells selected
when clicking
any individual or
header cell.
enum
DataGridViewSe
lectionMode
values:
ColumnHeaderSe
lect
RowHeaderSelec
t
FullColumnSele
ct
FullRowSelect
CellSelect
www.csetube.in
44
values:
ReadOnly
Appe
aranc
e
AlternatingRows
DefaultCellStyl
e
BackColor
BackgroundColor
BorderStyle
Indicates whether
user can modify
data in cells.
Values: TRue or
false .
SunkenHorizont
al
RaisedHorizont
al
The background
color of the grid.
SingleVertical
SunkenVertical
n
i
.
e
t
e
cs
ub
.
w
DataGridView
RaisedVertical
w
w
enum
BorderStyle
Raised
values:
ColumnCount
BorderStyle.Fi
xed3D
BorderStyle.Fi
xedSingle
BorderStyle.No
ne
Border style
applied to to
column/row
RowHeadersBorde headers.
ColumnHeadersBo
rderStyle
rStye
CellBorderStyle
enum
DataGridViewHe
aderBorderStyl
e values:
enum
DataGridViewCe
llBorderStyle
Custom
Raised
Sunk
www.csetube.in
45
None
Single
rows selected.
SelectedCells
Displays or
suppresses
headers. Values:
RowHeadersVisib true or false .
ColumnHeadersVi
sible
le
ColumnHeaderDef
aultCellStyle
DefaultCellStyl DataGridViewCe
e
llStyle object
b
u
et
cs
.
w
FirstDisplayedC
ell
GridColor
Colle Columns
ctions
n
i
.
e
w
w
Collection of all
grid columns.
Individual
columns are
accessed by an
index:
Columns[iI] .
Rows
Collection of all
grid rows.
Individual rows
are accessed by
an index:
Rows[i] .
SelectedColumns
Collection of
columns selected.
SelectedRows
Collection of
www.csetube.in
Collection of
cells selected.