15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

854 ❘ ChaPTer 30 cOre AdO.net<br />

Updating an existing row<br />

Updating an existing row within the DataTable is just a case of using the DataRow class’s indexer with<br />

either a column name or column number, as shown in the following code:<br />

r["RegionDescription"]="North West Engl<strong>and</strong>";<br />

r[1] = "North West Engl<strong>and</strong>";<br />

Both of these statements are equivalent (in this example):<br />

Changed RegionID 5 description<br />

1 Eastern Unchanged<br />

2 Western Unchanged<br />

3 Northern Unchanged<br />

4 Southern Unchanged<br />

5 North West Engl<strong>and</strong> Modified<br />

Prior to updating the database, the row updated has its state set to Modified as shown.<br />

Deleting a row<br />

Deleting a row is a matter of calling the Delete() method:<br />

r.Delete();<br />

A deleted row has its row state set to Deleted, but you cannot read columns from the deleted DataRow<br />

because they are no longer valid. When the adaptor’s Update() method is called, all deleted rows will use<br />

the DeleteComm<strong>and</strong>, which in this instance executes the RegionDelete stored procedure.<br />

Writing Xml output<br />

As you have seen already, the DataSet class has great support for defining its schema in XML, <strong>and</strong> just as<br />

you can read data from an XML document, you can also write data to an XML document.<br />

The DataSet.WriteXml() method enables you to output various parts of the data stored within the<br />

DataSet. You can elect to output just the data, or the data <strong>and</strong> the schema. The following code shows an<br />

example of both for the Region example shown earlier:<br />

ds.WriteXml(".\\WithoutSchema.xml");<br />

ds.WriteXml(".\\WithSchema.xml", XmlWriteMode.WriteSchema);<br />

The first file, WithoutSchema.xml, is shown here:<br />

<br />

<br />

<br />

1<br />

Eastern<br />

<br />

<br />

2<br />

Western<br />

<br />

<br />

3<br />

Northern<br />

<br />

<br />

4<br />

Southern<br />

<br />

<br />

<br />

<br />

<br />

<br />

code download WithoutSchema.xml<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!