using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Configuration; using System.Data.SqlClient; public class Form1 : Form { public Form1() { InitializeComponent(); } private void getData_Click(object sender, EventArgs e) { string orders = "SELECT * FROM Orders"; string customers = "SELECT * FROM Customers"; using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwind"].ConnectionString)) { SqlDataAdapter da = new SqlDataAdapter(orders, con); DataSet ds = new DataSet(); da.Fill(ds, "Orders"); da = new SqlDataAdapter(customers, con); da.Fill(ds, "Customers"); ds.Relations.Add("CustomerOrders", ds.Tables["Customers"].Columns["CustomerID"], ds.Tables["Orders"].Columns["CustomerID"]); DataViewManager dvm = new DataViewManager(ds); dvm.DataViewSettings["Customers"].RowFilter = "Country='UK'"; dataGrid1.SetDataBinding(dvm, "Customers"); } } private void InitializeComponent() { this.dataGrid1 = new System.Windows.Forms.DataGrid(); this.getData = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit(); this.SuspendLayout(); this.dataGrid1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGrid1.DataMember = ""; this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid1.Location = new System.Drawing.Point(13, 13); this.dataGrid1.Size = new System.Drawing.Size(488, 374); this.getData.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.getData.Location = new System.Drawing.Point(426, 393); this.getData.Size = new System.Drawing.Size(75, 23); this.getData.Text = "Get Data"; this.getData.UseVisualStyleBackColor = true; this.getData.Click += new System.EventHandler(this.getData_Click); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(513, 428); this.Controls.Add(this.getData); this.Controls.Add(this.dataGrid1); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit(); this.ResumeLayout(false); } private System.Windows.Forms.DataGrid dataGrid1; private System.Windows.Forms.Button getData; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } }
Populate a DataSet object with multiple DataTable objects by changing the CommandText property of a DataAdapter object's SelectCommand
using System; using System.Data; using System.Data.SqlClient; class MultipleDataTables2 { public static void Main() { SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa"); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 2 ProductID, ProductName, UnitPrice FROM Products ORDER BY ProductID"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); int numberOfRows = mySqlDataAdapter.Fill(myDataSet, "Products"); Console.WriteLine("numberOfRows = " + numberOfRows); mySqlDataAdapter.SelectCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers WHERE CustomerID = 'ALFKI'"; numberOfRows = mySqlDataAdapter.Fill(myDataSet, "Customers"); Console.WriteLine("numberOfRows = " + numberOfRows); mySqlConnection.Close(); foreach (DataTable myDataTable in myDataSet.Tables) { Console.WriteLine(" Reading from the " + myDataTable.TableName + " DataTable"); foreach (DataRow myDataRow in myDataTable.Rows) { foreach (DataColumn myDataColumn in myDataTable.Columns) { Console.WriteLine(myDataColumn + " = " + myDataRow[myDataColumn]); } } } } }
Read data from DataSet
using System; using System.Data; using System.Data.SqlClient; class PopDataset { static void Main() { string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI"; string sql = @"select * from employee"; SqlConnection conn = new SqlConnection(connString); try { conn.Open(); SqlDataAdapter da = new SqlDataAdapter(sql, conn); DataSet ds = new DataSet(); da.Fill(ds, "employee"); DataTable dt = ds.Tables["employee"]; foreach (DataRow row in dt.Rows) { foreach (DataColumn col in dt.Columns) Console.WriteLine(row[col]); Console.WriteLine("".PadLeft(20, '=')); } } catch(Exception e) { Console.WriteLine("Error: " + e); } finally { conn.Close(); } } }
Using Multi Tabled Datasets
/* * C# Programmers Pocket Consultant * Author: Gregory S. MacBeth * Email: gmacbeth@comporium.net * Create Date: June 27, 2003 * Last Modified Date: * Version: 1 */ using System; using System.Data; using System.Data.OleDb; namespace Client.Chapter_13___ADO.NET { public class UsingMultiTabledDatasets { static void Main(string[] args) { OleDbConnection MyConnection = new OleDbConnection(@"Provider=Microsft.Jet.OLEDB.4.0; Data Source = c:MyAccessDB.mdb"); OleDbDataAdapter MyAdapter = new OleDbDataAdapter("SELECT Column1, Column2, Column3 FROM MyTable", MyConnection); DataSet MyDataSet = new DataSet(); MyAdapter.Fill(MyDataSet, "MyTable"); foreach (DataTable MyTable in MyDataSet.Tables) { foreach (DataColumn MyColumn in MyTable.Columns) { foreach (DataRow MyRow in MyTable.Rows) { } } } } } }
Using Datasets
/* * C# Programmers Pocket Consultant * Author: Gregory S. MacBeth * Email: gmacbeth@comporium.net * Create Date: June 27, 2003 * Last Modified Date: * Version: 1 */ using System; using System.Data; using System.Data.SqlClient; namespace Client.Chapter_13___ADO.NET { public class UsingDatasets { static void Main(string[] args) { SqlConnection MyConnection = new SqlConnection(@"Data Source=(local); Initial Catalog = CaseManager; Integrated Security=true"); SqlDataAdapter MyAdapter = new SqlDataAdapter("SELECT * FROM CaseInfo", MyConnection); DataSet MyDataSet = new DataSet(); MyAdapter.Fill(MyDataSet, "MyTable"); MyDataSet.WriteXml(@"c:MyDatSet.xml"); } } }
Populate a DataSet object with a range of rows from a SELECT statement
using System; using System.Data; using System.Data.SqlClient; class PopulateDataSetUsingRange { public static void Main() { SqlConnection mySqlConnection =new SqlConnection("server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;"); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT TOP 5 ID, FirstName, LastName " + "FROM Employee " + "ORDER BY ID"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); Console.WriteLine("Retrieving rows from the Employee table"); int numberOfRows = mySqlDataAdapter.Fill(myDataSet, 1, 3, "Employee"); Console.WriteLine("numberOfRows = " + numberOfRows); mySqlConnection.Close(); DataTable myDataTable = myDataSet.Tables["Employee"]; foreach (DataRow myDataRow in myDataTable.Rows) { Console.WriteLine("ID = " + myDataRow["ID"]); Console.WriteLine("FirstName = " + myDataRow["FirstName"]); Console.WriteLine("LastName = " + myDataRow["LastName"]); } } }
Open the XML file and read into a DataSet
using System;
using System.IO;
using System.Data;
public class MainClass {
static void Main(string[] args) {
if (args.Length != 1)
return;
FileStream fs = new FileStream(args[0], FileMode.Open);
DataSet ds = new DataSet();
ds.ReadXml(fs);
// Use a DataTable to display the members.
DataTable mt = ds.Tables[“member”];
for (int row = 0; row < mt.Rows.Count; row++) {
for (int col = 0; col < mt.Columns.Count - 1; col++) {
Console.WriteLine("{0,-10}{1}",
mt.Columns[col].Caption,
mt.Rows[row][col].ToString().Trim());
}
Console.WriteLine();
}
fs.Close();
}
}
[/csharp]