|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
4 Data Sets4.1 DataSet Methods
4.2 DataSet Properties
4.3 Loading A DataSet4.3.1 From a TableTables created and filled with data as discussed in the Tables section can be
added to the Tables collection by using the Add() method or they can be added at
once using the Example of Two equivalent methods used to add tables dtElements and
dtIsotopes to the DataSet ElementDS using Add() and AddRange() Method 1 – // Add the Elements table to the DataSet
elementDS.Tables.Add(dtElements);
// Add the Isotopes table to the DataSet
elementDS.Tables.Add(dtIsotopes);
Method 2 – ElementDS.Tables.AddRange(new DataTable()
{dtElements, dtIsotopes});
4.3.2 From a DatabaseA DataSet tables collection can also be filled with linked tables containing data directly from a database recordset, which is considered bound data. 4.3.2.1 Method 1 –
sqlDataAdapter
The following code illustrates how to directly load or bind a database
recordset using the sqlDataAdapter’s System.Data.SqlClient.SqlConnection sqlConnection1;
System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1;
System.Data.SqlClient.SqlCommand sqlSelectCommand1;
sqlConnection1 = new System.Data.SqlClient.SqlConnection();
sqlDataAdapter1 = new System.Data.SqlClient.SqlDataAdapter();
sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();
sqlSelectCommand1.CommandText = "SELECT ElementsID, AtomicNbr,”
+ “Symbol, AtomicMass, Element FROM [Elements]";
sqlDataAdapter1.SelectCommand = sqlSelectCommand1;
//
// sqlConnection1
// <replace xxxxx, nnnnn and dbName with appropriate values>
//
sqlConnection1.ConnectionString = “workstation id=xxxxx;packet “
+ “ size=4096;user id=nnnnn; pwd=yyyyy;data “
+ “ source=xxxxx; persist”
+ “ security info=False; initial catalog=dbName”;
sqlSelectCommand1.Connection = sqlConnection1;
DataSet ds = new DataSet();
sqlDataAdapter1.Fill(ds);
4.3.2.2 Method 2 – sqlDataReaderThis method is more complex than using the sqlDataAdapter’s string SQL= "SELECT ElementsID, AtomicNbr, " +
"Symbol, AtomicMass, Element”
+ “ FROM [Elements] order by AtomicNbr ASC";
sqlConnection sqlConnection1=
new sqlConnection (
"connection info to MSDE or SQL Server 2000+”;);
sqlCommand sqlCommand = new sqlCommand (SQL,sqlConnection1);
sqlConnection1.Open();
sqlDataReader elementReader = SqlCommand.ExecuteReader();
// Starting with the element table dt defined in
// the Tables section, an ElementID column
// is added that will be used as the primary key for the row.
DataColumn dc = new DataColumn(“ElementsID”,
System.Type.GetType(“System.Guid”));
dt.Columns.Add(dc);
// Make ‘ElementsID’ a primary key:
dt.PrimaryKey = new DataColumn[]{dt.Columns["ElementsID"]};
// Fill table dt with data from the database table Elements:
Note: the sqlDataReader class has a method that can be used to determine whether a null or non-existent value was returned for a particular cell. For example: If (!elementReader.IsDBNull(elementReader.GetOrdinal("AtomicNbr")))
{
// fill cell with value
}
else
{
// handle this condition
// for example fill cell with a default value
}
This check has been omitted in the following code for clarity, but it is a good practice to use it. DataRow dr;
int PrevAtomicNbr = 0;
try
{
while(myReader.Read())
{
if (PrevAtomicNbr != elementReader.GetInt32(
elementReader.GetOrdinal("AtomicNbr")))
{
PrevAtomicNbr = elementReader.GetInt32(
elementReader.GetOrdinal("AtomicNbr"));
dr = dt.NewRow();
dr[“ElementsID”] =
elementReader.GetGuid(elementReader.GetOrdinal("ElementsID"));
dr[“AtomicNbr”] = elementReader.GetInt32(
elementReader.GetOrdinal("AtomicNbr"));
dr[“Symbol”] = elementReader.GetString(
elementReader.GetOrdinal("Symbol));
dr[“Element”] = elementReader.GetString(
elementReader.GetOrdinal("Element"));
dr[“AtomicMass”] =
elementReader.GetDecimal(elementReader.GetOrdinal("AtomicMass"));
dt.Rows.Add(dr);
}
}
}
finally
{
elementReader.Close();
sqlConnection1.Close();
}
dt.AcceptChanges();
// Add table dt to a new dataset ds and its tables collection
DataSet ds = new DataSet();
ds.Tables.Add(dt);
4.4 Linked TablesThis example shows how to link two tables together through a primary key. In this example a Table with TableName of Elements is created with a Primary key of ‘Atomic Number’. The second Table with TableName of Isotopes is linked through a relationship coupling its Atomic Number column to Elements primary key. // create a new DataSet named Periodic that will
// hold two linked tables with
// TableNames of Elements and Isotopes respectively.
DataSet elementDS = new DataSet("Periodic");
// Create Elements Table
DataTable dtElements = new DataTable("Elements");
dtElements.Columns.Add("Atomic Number", typeof(int));
dtElements.Columns.Add("Element", typeof(string));
dtElements.Columns.Add("Symbol", typeof(string));
// Make ‘Atomic Number’ a primary key in Elements table
dtElements.PrimaryKey = new DataColumn[]
{dtElements.Columns["Atomic Number"]};
// Create Isotopes Table
DataTable dtIsotopes = new DataTable("Isotopes");
dtIsotopes.Columns.Add("Symbol", typeof(string));
dtIsotopes.Columns.Add("Atomic Number", typeof(int));
dtIsotopes.Columns.Add("Isotope Number",typeof(int));
dtIsotopes.Columns.Add("Percent Abundance",
typeof(System.Decimal))
dtIsotopes.Columns.Add("Atomic Mass", typeof(System.Decimal));
// Add tables to the Dataset
ElementDS.Tables.AddRange(new DataTable(){dtElements, dtIsotopes});
Dataset . // Add a relationship for Tables Elements and Isotopes
// through the primary key ‘Atomic Number’ in DataSet
// Periodic and name the relationship ‘Isotopes’. This name is
// used in the DataGrid to select table rows, in table Isotopes,
// that contain isotope values for the selected element.
elementDS.Relations.Add("Isotopes",
elementDS.Tables["Elements"].Columns["Atomic Number"],
elementDS.Tables["Isotopes"].Columns["Atomic Number"] );
4.5 Linked tables in a dataset4.5.1 FillingAssume that another DataSet ds exists that has a table with index 0 in its Tables collection that contains both Element and Isotope data that will be used to fill rows in the linked tables contained in the elementDS DataSet tables collection as defined in the previous section. Assume Table[0] in DataSet ds has the following columns: AtomicNbr, Element, Symbol, IsotopeNbr, PctAbundance and AtomicMass where rows are sorted by Atomic numbers ascending and then by IsotopeNbr numbers ascending. // Assign the table containing both Elements and
// Isotopes to dt using index 0
DataTable dt = ds.Tables[0];
// Create two DataTable variables dtElements and dtIsotopes and
// assign tables contained in the DataSet elementDS Tables
// collection using TableNames as indexes.
DataTable dtElements = elementDS.Tables[“Elements”];
DataTable dtIsotopes = elementDS.Tables[“Isotopes”];
DataRow drElement;
DataRow drIsotope;
int prevAtomicNbr = 0;
foreach (DataRow dr in dt.Rows)
{
if(prevAtomicNbr != (int)dr["AtomicNbr"])
{ //need only one row per AtomicNbr in Table[“Elements”]
// Fill an element row with data from dt.
prevAtomicNbr = (int)dr["AtomicNbr"];
drElement = dtElements.NewRow();
drElement["Atomic Number"] = dr["AtomicNbr"];
drElement["Element"] = dr["Element"];
drElement["Symbol"] = dr["Symbol"];
dtElements.Rows.Add(drElement);
}
// Fill an isotope row with data from dt.
drIsotope = dtIsotopes.NewRow();
drIsotope["Isotope Number"] = dr["IsotopeNbr"];
drIsotope["Symbol"] = dr["Symbol"];
drIsotope["Atomic Number"] = dr["AtomicNbr"];
drIsotope["Percent Abundance"] = dr["PctAbundance"];
drIsotope["Atomic Mass"] = dr["AtomicMass"];
dtIsotopes.Rows.Add(drIsotope);
}
4.5.2 RemovingTo remove all linked tables or a selected table that is linked from the The following code example provides a generic routine for removing all linked tables in a dataset. public void RemoveAllTables(DataSet ds)
{
// need to do it in reverse order due to constraints
ds.Relations.Clear();
for (int i=ds.Tables.Count -1; i >=0; i--)
{
ds.Tables[i].Constraints.Clear();
ds.Tables.RemoveAt(i);
}
}
4.6 XML Export and Import DataSet Data4.6.1
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||