using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data.SqlClient;
public class Queries : System.Windows.Forms.Form {
private System.Windows.Forms.TextBox txtResult;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button cmdExecute;
private System.Windows.Forms.TextBox txtSql;
private System.ComponentModel.Container components = null;
public Queries() {
InitializeComponent();
}
private void InitializeComponent() {
this.txtSql = new System.Windows.Forms.TextBox();
this.txtResult = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.cmdExecute = new System.Windows.Forms.Button();
this.SuspendLayout();
this.txtSql.Location = new System.Drawing.Point(0, 32);
this.txtSql.Multiline = true;
this.txtSql.Name = "txtSql";
this.txtSql.Size = new System.Drawing.Size(400, 72);
this.txtSql.TabIndex = 0;
this.txtSql.Text = "";
this.txtResult.Location = new System.Drawing.Point(0, 184);
this.txtResult.Multiline = true;
this.txtResult.Name = "txtResult";
this.txtResult.Size = new System.Drawing.Size(400, 88);
this.txtResult.TabIndex = 1;
this.txtResult.Text = "";
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(384, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Type a SQL statement in the text box.";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label2.Location = new System.Drawing.Point(0, 160);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(392, 16);
this.label2.TabIndex = 3;
this.label2.Text = "Execution Result";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExecute.Location = new System.Drawing.Point(152, 112);
this.cmdExecute.Name = "cmdExecute";
this.cmdExecute.Size = new System.Drawing.Size(104, 32);
this.cmdExecute.TabIndex = 4;
this.cmdExecute.Text = "Execute Command";
this.cmdExecute.Click += new System.EventHandler(this.cmdExecute_Click);
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(400, 275);
this.Controls.Add(this.cmdExecute);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtResult);
this.Controls.Add(this.txtSql);
this.Name = "Queries";
this.Text = "Tables and Relationships";
this.ResumeLayout(false);
}
private void cmdExecute_Click(object sender, System.EventArgs e) {
try{
SqlConnection conn = new SqlConnection(@"server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");
conn.Open();
string strSQL=txtSql.Text;
SqlCommand cmd= new SqlCommand(strSQL, conn);
cmd.ExecuteReader();
conn.Close();
txtResult.Text = "SQL executed successfully.";
} catch (System.Data.SqlClient.SqlException ex) {
txtResult.Text =
"There was an error in executing the SQL. " +
"Error Message:" + ex.Message;
}
}
static void Main() {
Application.Run(new Queries());
}
}
Month: February 2011
Write data in database table to XML file
using System;
using System.Data;
using System.Data.SqlClient;
class WriteXML {
static void Main(){
string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";
string qry = @"select * from employee";
SqlConnection conn = new SqlConnection(connString);
try{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(qry, conn);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds, "employee");
ds.WriteXml(@"employee.xml");
} catch(Exception e) {
Console.WriteLine("Error: " + e);
} finally {
conn.Close();
}
}
}
Use the ExecuteXmlReader() method to run a SELECT statement that returns XML
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
class ExecuteXmlReader
{
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 " +
"FOR XML AUTO";
mySqlConnection.Open();
XmlReader myXmlReader = mySqlCommand.ExecuteXmlReader();
myXmlReader.Read();
while (!myXmlReader.EOF) {
Console.WriteLine(myXmlReader.ReadOuterXml());
}
myXmlReader.Close();
mySqlConnection.Close();
}
}
How to write and read XML files
using System;
using System.Data;
using System.Data.SqlClient;
class WriteAndReadXML {
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 CustomerID, CompanyName, ContactName, " +
"Address " +
"FROM Customers " +
"ORDER BY CustomerID";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet, "Customers");
mySqlConnection.Close();
myDataSet.WriteXml("myXmlFile.xml");
myDataSet.WriteXml("myXmlFile2.xml", XmlWriteMode.WriteSchema);
myDataSet.WriteXmlSchema("myXmlSchemaFile.xml");
myDataSet.Clear();
myDataSet.ReadXml("myXmlFile.xml");
DataTable myDataTable = myDataSet.Tables["Customers"];
foreach (DataRow myDataRow in myDataTable.Rows) {
Console.WriteLine("CustomerID = " + myDataRow["CustomerID"]);
Console.WriteLine("CompanyName = " + myDataRow["CompanyName"]);
Console.WriteLine("ContactName = " + myDataRow["ContactName"]);
Console.WriteLine("Address = " + myDataRow["Address"]);
}
}
}
Fill Data from database table to ListView
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
public class Form1 : System.Windows.Forms.Form {
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button cmdExecute;
private System.Windows.Forms.TextBox txtSql;
private System.Windows.Forms.ListView lvwResult;
private System.ComponentModel.Container components = null;
public Form1() {
InitializeComponent();
}
private void InitializeComponent() {
this.label1 = new System.Windows.Forms.Label();
this.cmdExecute = new System.Windows.Forms.Button();
this.txtSql = new System.Windows.Forms.TextBox();
this.lvwResult = new System.Windows.Forms.ListView();
this.SuspendLayout();
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = “label1”;
this.label1.Size = new System.Drawing.Size(296, 16);
this.label1.TabIndex = 0;
this.label1.Text = “Enter a SQL query or statement and click Execute.”;
this.cmdExecute.Location = new System.Drawing.Point(227, 224);
this.cmdExecute.Name = “cmdExecute”;
this.cmdExecute.TabIndex = 1;
this.cmdExecute.Text = “Execute”;
this.cmdExecute.Click += new System.EventHandler(this.cmdExecute_Click);
this.txtSql.Location = new System.Drawing.Point(0, 16);
this.txtSql.Multiline = true;
this.txtSql.Name = “txtSql”;
this.txtSql.Size = new System.Drawing.Size(528, 200);
this.txtSql.TabIndex = 2;
this.txtSql.Text = “”;
this.lvwResult.GridLines = true;
this.lvwResult.Location = new System.Drawing.Point(0, 256);
this.lvwResult.Name = “lvwResult”;
this.lvwResult.Size = new System.Drawing.Size(528, 200);
this.lvwResult.TabIndex = 3;
this.lvwResult.View = System.Windows.Forms.View.Details;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(528, 452);
this.Controls.Add(this.lvwResult);
this.Controls.Add(this.txtSql);
this.Controls.Add(this.cmdExecute);
this.Controls.Add(this.label1);
this.Name = “Form1”;
this.Text = “Query Processor”;
this.ResumeLayout(false);
}
static void Main() {
Application.Run(new Form1());
}
private void cmdExecute_Click(object sender, System.EventArgs e) {
SqlConnection conn = new SqlConnection(“server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI”);
try {
lvwResult.Columns.Clear() ;
lvwResult.Items.Clear();
conn.Open();
txtSql.Text =”select * from Employee”;
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = txtSql.Text;
SqlDataReader dr = cmd.ExecuteReader();
for (int i = 0; i< dr.FieldCount; i++) { ColumnHeader ch = new ColumnHeader(); ch.Text=dr.GetName(i); lvwResult.Columns.Add(ch); } ListViewItem itmX; while (dr.Read()) { itmX=new ListViewItem(); itmX.Text= dr.GetValue(0).ToString(); for (int i=1 ; i< dr.FieldCount; i++) { itmX.SubItems.Add(dr.GetValue(i).ToString()); } lvwResult.Items.Add(itmX); } dr.Close(); } catch ( System.Data.SqlClient.SqlException ex) { Console.WriteLine("There was an error in executing the SQL." + " Error Message:" + ex.Message, "SQL"); } finally { conn.Close(); } } } [/csharp]
Data Binding 4
/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury,
Zach Greenvoss, Shripad Kulkarni, Neil Whitlow
Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace DataBinding
{
/// <summary>
/// Summary description for DataBinding4.
/// </summary>
public class DataBinding4 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid grdOrders;
private System.Windows.Forms.DataGrid grdOrderDetails;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox cbCust;
private System.Windows.Forms.TextBox txtPhoneNo;
private System.Windows.Forms.TextBox txtFaxNo;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtContact;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public DataBinding4()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
SqlConnection cn=new SqlConnection(@"data source=(local);uid=sa;password=;database=northwind");
DataSet ds = new DataSet("CustOrders");
SqlDataAdapter daCust=new SqlDataAdapter("select * from customers;select * from orders;select * from [order details]",cn);
daCust.Fill(ds);
ds.Relations.Add("CustOrder",ds.Tables["Table"].Columns["customerid"],ds.Tables["Table1"].Columns["customerid"]);
ds.Relations.Add("OrderDetail",ds.Tables["Table1"].Columns["orderid"],ds.Tables["Table2"].Columns["orderid"]);
grdOrders.DataSource=ds;
grdOrders.DataMember="Table.CustOrder";
grdOrderDetails.DataSource=ds;
grdOrderDetails.DataMember="Table.CustOrder.OrderDetail";
cbCust.DataSource=ds;
cbCust.DisplayMember="Table.CompanyName";
txtContact.DataBindings.Add("Text",ds,"Table.ContactName");
txtPhoneNo.DataBindings.Add("Text",ds,"Table.Phone");
txtFaxNo.DataBindings.Add("Text",ds,"Table.Fax");
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.grdOrders = new System.Windows.Forms.DataGrid();
this.grdOrderDetails = new System.Windows.Forms.DataGrid();
this.cbCust = new System.Windows.Forms.ComboBox();
this.txtPhoneNo = new System.Windows.Forms.TextBox();
this.txtFaxNo = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.txtContact = new System.Windows.Forms.TextBox();
((System.ComponentModel.ISupportInitialize)(this.grdOrders)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.grdOrderDetails)).BeginInit();
this.SuspendLayout();
//
// grdOrders
//
this.grdOrders.AllowNavigation = false;
this.grdOrders.DataMember = "";
this.grdOrders.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.grdOrders.Location = new System.Drawing.Point(40, 176);
this.grdOrders.Name = "grdOrders";
this.grdOrders.Size = new System.Drawing.Size(448, 144);
this.grdOrders.TabIndex = 1;
//
// grdOrderDetails
//
this.grdOrderDetails.DataMember = "";
this.grdOrderDetails.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.grdOrderDetails.Location = new System.Drawing.Point(40, 328);
this.grdOrderDetails.Name = "grdOrderDetails";
this.grdOrderDetails.Size = new System.Drawing.Size(448, 136);
this.grdOrderDetails.TabIndex = 2;
//
// cbCust
//
this.cbCust.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbCust.Location = new System.Drawing.Point(216, 32);
this.cbCust.Name = "cbCust";
this.cbCust.Size = new System.Drawing.Size(240, 21);
this.cbCust.TabIndex = 3;
//
// txtPhoneNo
//
this.txtPhoneNo.Location = new System.Drawing.Point(216, 96);
this.txtPhoneNo.Name = "txtPhoneNo";
this.txtPhoneNo.Size = new System.Drawing.Size(240, 20);
this.txtPhoneNo.TabIndex = 4;
this.txtPhoneNo.Text = "textBox1";
//
// txtFaxNo
//
this.txtFaxNo.Location = new System.Drawing.Point(216, 128);
this.txtFaxNo.Name = "txtFaxNo";
this.txtFaxNo.Size = new System.Drawing.Size(240, 20);
this.txtFaxNo.TabIndex = 5;
this.txtFaxNo.Text = "textBox2";
//
// label1
//
this.label1.Location = new System.Drawing.Point(80, 32);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(128, 24);
this.label1.TabIndex = 6;
this.label1.Text = "Customer Name";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label2
//
this.label2.Location = new System.Drawing.Point(80, 96);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(128, 24);
this.label2.TabIndex = 7;
this.label2.Text = "Phone Number";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label3
//
this.label3.Location = new System.Drawing.Point(80, 128);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(128, 24);
this.label3.TabIndex = 8;
this.label3.Text = "Fax Number";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label4
//
this.label4.Location = new System.Drawing.Point(80, 64);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(128, 24);
this.label4.TabIndex = 10;
this.label4.Text = "Contact Name";
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// txtContact
//
this.txtContact.Location = new System.Drawing.Point(216, 64);
this.txtContact.Name = "txtContact";
this.txtContact.Size = new System.Drawing.Size(240, 20);
this.txtContact.TabIndex = 9;
this.txtContact.Text = "textBox1";
//
// DataBinding4
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(520, 483);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.label4,
this.txtContact,
this.label3,
this.label2,
this.label1,
this.txtFaxNo,
this.txtPhoneNo,
this.cbCust,
this.grdOrderDetails,
this.grdOrders});
this.Name = "DataBinding4";
this.Text = "DataBinding4";
((System.ComponentModel.ISupportInitialize)(this.grdOrders)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.grdOrderDetails)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new DataBinding4());
}
}
}
Data Binding 3
/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury,
Zach Greenvoss, Shripad Kulkarni, Neil Whitlow
Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace DataBinding_3
{
/// <summary>
/// Summary description for DataBinding_3.
/// </summary>
public class DataBinding_3 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid grdOrders;
private System.Windows.Forms.DataGrid grdOrderDetails;
private System.Windows.Forms.DataGrid grdCustomers;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public DataBinding_3()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
SqlConnection cn=new SqlConnection(@"data source=(local);uid=sa;password=;database=northwind");
DataSet ds = new DataSet("CustOrders");
SqlDataAdapter daCust=new SqlDataAdapter("select * from customers;select * from orders;select * from [order details]",cn);
daCust.Fill(ds);
ds.Relations.Add("CustOrder",ds.Tables["Table"].Columns["customerid"],ds.Tables["Table1"].Columns["customerid"]);
ds.Relations.Add("OrderDetail",ds.Tables["Table1"].Columns["orderid"],ds.Tables["Table2"].Columns["orderid"]);
grdCustomers.DataSource=ds;
grdCustomers.DataMember="Table";
grdOrders.DataSource=ds;
grdOrders.DataMember="Table.CustOrder";
grdOrderDetails.DataSource=ds;
grdOrderDetails.DataMember="Table.CustOrder.OrderDetail";
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.grdCustomers = new System.Windows.Forms.DataGrid();
this.grdOrders = new System.Windows.Forms.DataGrid();
this.grdOrderDetails = new System.Windows.Forms.DataGrid();
((System.ComponentModel.ISupportInitialize)(this.grdCustomers)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.grdOrders)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.grdOrderDetails)).BeginInit();
this.SuspendLayout();
//
// grdCustomers
//
this.grdCustomers.AllowNavigation = false;
this.grdCustomers.DataMember = "";
this.grdCustomers.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.grdCustomers.Location = new System.Drawing.Point(40, 16);
this.grdCustomers.Name = "grdCustomers";
this.grdCustomers.Size = new System.Drawing.Size(448, 152);
this.grdCustomers.TabIndex = 0;
//
// grdOrders
//
this.grdOrders.AllowNavigation = false;
this.grdOrders.DataMember = "";
this.grdOrders.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.grdOrders.Location = new System.Drawing.Point(40, 176);
this.grdOrders.Name = "grdOrders";
this.grdOrders.Size = new System.Drawing.Size(448, 144);
this.grdOrders.TabIndex = 1;
//
// grdOrderDetails
//
this.grdOrderDetails.DataMember = "";
this.grdOrderDetails.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.grdOrderDetails.Location = new System.Drawing.Point(40, 328);
this.grdOrderDetails.Name = "grdOrderDetails";
this.grdOrderDetails.Size = new System.Drawing.Size(448, 136);
this.grdOrderDetails.TabIndex = 2;
//
// DataBinding_3
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(528, 483);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.grdOrderDetails,
this.grdOrders,
this.grdCustomers});
this.Name = "DataBinding_3";
this.Text = "DataBinding_3";
((System.ComponentModel.ISupportInitialize)(this.grdCustomers)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.grdOrders)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.grdOrderDetails)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new DataBinding_3());
}
}
}

