ADO Example
This exmaple gives you complete view of Insert, Update, DataSet etc ,, of ADO.net
using System;
using System.Reflection;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using ADODB;
public class frmMain : System.Windows.Forms.Form
{
protected const string MSDE_CONNECTION_STRING = "driver={SQL Server};server=(local)/VSDotNet;uid=;pwd=;database=Customer";
protected const string SQL_CONNECTION_STRING = "driver={SQL Server};server=localhost;uid=;pwd=;database=Customer";
private string Connectionstring = SQL_CONNECTION_STRING;
private bool HasConnected = false;
Connection cnn = new Connection();
Command cm = new Command();
Recordset rs = new Recordset();
#region " Windows Form Designer generated code "
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.Run(new frmMain());
}
public frmMain()
{
//This call is required by the Windows Form Designer.
InitializeComponent();
//Add any initialization after the InitializeComponent() call
// So that we only need to set the title of the application once,
// we use the AssemblyInfo class (defined in the AssemblyInfo.cs file)
// to read the AssemblyTitle attribute.
AssemblyInfo ainfo = new AssemblyInfo();
this.Text = ainfo.Title;
this.mnuAbout.Text = string.Format("&About {0} ...", ainfo.Title);
PopulateSimpleNavigationForm();
}
//Form overrides dispose to clean up the component list.
protected override void Dispose(bool disposing) {
if (disposing) {
if (components != null) {
components.Dispose();
}
}
base.Dispose(disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components = null;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
private System.Windows.Forms.MainMenu mnuMain;
private System.Windows.Forms.MenuItem mnuFile;
private System.Windows.Forms.MenuItem mnuExit;
private System.Windows.Forms.MenuItem mnuHelp;
private System.Windows.Forms.MenuItem mnuAbout;
private System.Windows.Forms.TabControl tcMain;
private System.Windows.Forms.TabPage tpDatasetExample;
private System.Windows.Forms.Button btnDataset;
private System.Windows.Forms.DataGrid dgMain;
private System.Windows.Forms.TabPage tpRecordNavigation;
private System.Windows.Forms.TextBox txtPhone;
private System.Windows.Forms.TextBox txtContactName;
private System.Windows.Forms.TextBox txtCompanyName;
private System.Windows.Forms.Button btnFirst;
private System.Windows.Forms.Button btnPrev;
private System.Windows.Forms.Button btnNext;
private System.Windows.Forms.Button btnLast;
private System.Windows.Forms.TabPage tpInsert;
private System.Windows.Forms.TextBox txtCategoryName;
private System.Windows.Forms.TextBox txtDescription;
private System.Windows.Forms.Button btnInsert;
private System.Windows.Forms.Label lblCategoryName;
private System.Windows.Forms.Label Label1;
private System.Windows.Forms.TabPage tpUpdate;
private System.Windows.Forms.Button btnUpdate;
private System.Windows.Forms.Label Label2;
private System.Windows.Forms.Label Label3;
private System.Windows.Forms.Label Label4;
private System.Windows.Forms.Label Label5;
private System.Windows.Forms.Label Label6;
private System.Windows.Forms.ComboBox cbCategoryName;
private System.Windows.Forms.TextBox txtUpdateDescription;
private System.Windows.Forms.Label Label7;
private System.Windows.Forms.Label Label8;
private System.Windows.Forms.Label Label9;
private System.Windows.Forms.Label Label10;
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
this.mnuMain = new System.Windows.Forms.MainMenu(this.components);
this.mnuFile = new System.Windows.Forms.MenuItem();
this.mnuExit = new System.Windows.Forms.MenuItem();
this.mnuHelp = new System.Windows.Forms.MenuItem();
this.mnuAbout = new System.Windows.Forms.MenuItem();
this.tcMain = new System.Windows.Forms.TabControl();
this.tpRecordNavigation = new System.Windows.Forms.TabPage();
this.Label7 = new System.Windows.Forms.Label();
this.Label6 = new System.Windows.Forms.Label();
this.Label5 = new System.Windows.Forms.Label();
this.Label4 = new System.Windows.Forms.Label();
this.btnLast = new System.Windows.Forms.Button();
this.btnNext = new System.Windows.Forms.Button();
this.btnPrev = new System.Windows.Forms.Button();
this.btnFirst = new System.Windows.Forms.Button();
this.txtPhone = new System.Windows.Forms.TextBox();
this.txtContactName = new System.Windows.Forms.TextBox();
this.txtCompanyName = new System.Windows.Forms.TextBox();
this.tpInsert = new System.Windows.Forms.TabPage();
this.Label8 = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
this.lblCategoryName = new System.Windows.Forms.Label();
this.btnInsert = new System.Windows.Forms.Button();
this.txtDescription = new System.Windows.Forms.TextBox();
this.txtCategoryName = new System.Windows.Forms.TextBox();
this.tpUpdate = new System.Windows.Forms.TabPage();
this.Label9 = new System.Windows.Forms.Label();
this.Label2 = new System.Windows.Forms.Label();
this.Label3 = new System.Windows.Forms.Label();
this.txtUpdateDescription = new System.Windows.Forms.TextBox();
this.cbCategoryName = new System.Windows.Forms.ComboBox();
this.btnUpdate = new System.Windows.Forms.Button();
this.tpDatasetExample = new System.Windows.Forms.TabPage();
this.Label10 = new System.Windows.Forms.Label();
this.btnDataset = new System.Windows.Forms.Button();
this.dgMain = new System.Windows.Forms.DataGrid();
this.tcMain.SuspendLayout();
this.tpRecordNavigation.SuspendLayout();
this.tpInsert.SuspendLayout();
this.tpUpdate.SuspendLayout();
this.tpDatasetExample.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgMain)).BeginInit();
this.SuspendLayout();
//
// mnuMain
//
this.mnuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuFile,
this.mnuHelp});
//
// mnuFile
//
this.mnuFile.Index = 0;
this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuExit});
resources.ApplyResources(this.mnuFile, "mnuFile");
//
// mnuExit
//
this.mnuExit.Index = 0;
resources.ApplyResources(this.mnuExit, "mnuExit");
this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click);
//
// mnuHelp
//
this.mnuHelp.Index = 1;
this.mnuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuAbout});
resources.ApplyResources(this.mnuHelp, "mnuHelp");
//
// mnuAbout
//
this.mnuAbout.Index = 0;
resources.ApplyResources(this.mnuAbout, "mnuAbout");
this.mnuAbout.Click += new System.EventHandler(this.mnuAbout_Click);
//
// tcMain
//
resources.ApplyResources(this.tcMain, "tcMain");
this.tcMain.Controls.Add(this.tpRecordNavigation);
this.tcMain.Controls.Add(this.tpInsert);
this.tcMain.Controls.Add(this.tpUpdate);
this.tcMain.Controls.Add(this.tpDatasetExample);
this.tcMain.Name = "tcMain";
this.tcMain.SelectedIndex = 0;
this.tcMain.SelectedIndexChanged += new System.EventHandler(this.tcMain_SelectedIndexChanged);
//
// tpRecordNavigation
//
this.tpRecordNavigation.Controls.Add(this.Label7);
this.tpRecordNavigation.Controls.Add(this.Label6);
this.tpRecordNavigation.Controls.Add(this.Label5);
this.tpRecordNavigation.Controls.Add(this.Label4);
this.tpRecordNavigation.Controls.Add(this.btnLast);
this.tpRecordNavigation.Controls.Add(this.btnNext);
this.tpRecordNavigation.Controls.Add(this.btnPrev);
this.tpRecordNavigation.Controls.Add(this.btnFirst);
this.tpRecordNavigation.Controls.Add(this.txtPhone);
this.tpRecordNavigation.Controls.Add(this.txtContactName);
this.tpRecordNavigation.Controls.Add(this.txtCompanyName);
resources.ApplyResources(this.tpRecordNavigation, "tpRecordNavigation");
this.tpRecordNavigation.Name = "tpRecordNavigation";
this.tpRecordNavigation.Click += new System.EventHandler(this.tpRecordNavigation_Click);
//
// Label7
//
resources.ApplyResources(this.Label7, "Label7");
this.Label7.ForeColor = System.Drawing.Color.Blue;
this.Label7.Name = "Label7";
//
// Label6
//
resources.ApplyResources(this.Label6, "Label6");
this.Label6.Name = "Label6";
//
// Label5
//
resources.ApplyResources(this.Label5, "Label5");
this.Label5.Name = "Label5";
//
// Label4
//
resources.ApplyResources(this.Label4, "Label4");
this.Label4.Name = "Label4";
//
// btnLast
//
resources.ApplyResources(this.btnLast, "btnLast");
this.btnLast.Name = "btnLast";
this.btnLast.Click += new System.EventHandler(this.btnLast_Click);
//
// btnNext
//
resources.ApplyResources(this.btnNext, "btnNext");
this.btnNext.Name = "btnNext";
this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
//
// btnPrev
//
resources.ApplyResources(this.btnPrev, "btnPrev");
this.btnPrev.Name = "btnPrev";
this.btnPrev.Click += new System.EventHandler(this.btnPrev_Click);
//
// btnFirst
//
resources.ApplyResources(this.btnFirst, "btnFirst");
this.btnFirst.Name = "btnFirst";
this.btnFirst.Click += new System.EventHandler(this.btnFirst_Click);
//
// txtPhone
//
resources.ApplyResources(this.txtPhone, "txtPhone");
this.txtPhone.Name = "txtPhone";
//
// txtContactName
//
resources.ApplyResources(this.txtContactName, "txtContactName");
this.txtContactName.Name = "txtContactName";
//
// txtCompanyName
//
resources.ApplyResources(this.txtCompanyName, "txtCompanyName");
this.txtCompanyName.Name = "txtCompanyName";
//
// tpInsert
//
this.tpInsert.Controls.Add(this.Label8);
this.tpInsert.Controls.Add(this.Label1);
this.tpInsert.Controls.Add(this.lblCategoryName);
this.tpInsert.Controls.Add(this.btnInsert);
this.tpInsert.Controls.Add(this.txtDescription);
this.tpInsert.Controls.Add(this.txtCategoryName);
resources.ApplyResources(this.tpInsert, "tpInsert");
this.tpInsert.Name = "tpInsert";
//
// Label8
//
resources.ApplyResources(this.Label8, "Label8");
this.Label8.ForeColor = System.Drawing.Color.Blue;
this.Label8.Name = "Label8";
//
// Label1
//
resources.ApplyResources(this.Label1, "Label1");
this.Label1.Name = "Label1";
//
// lblCategoryName
//
resources.ApplyResources(this.lblCategoryName, "lblCategoryName");
this.lblCategoryName.Name = "lblCategoryName";
//
// btnInsert
//
resources.ApplyResources(this.btnInsert, "btnInsert");
this.btnInsert.Name = "btnInsert";
this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click);
//
// txtDescription
//
resources.ApplyResources(this.txtDescription, "txtDescription");
this.txtDescription.Name = "txtDescription";
//
// txtCategoryName
//
resources.ApplyResources(this.txtCategoryName, "txtCategoryName");
this.txtCategoryName.Name = "txtCategoryName";
//
// tpUpdate
//
this.tpUpdate.Controls.Add(this.Label9);
this.tpUpdate.Controls.Add(this.Label2);
this.tpUpdate.Controls.Add(this.Label3);
this.tpUpdate.Controls.Add(this.txtUpdateDescription);
this.tpUpdate.Controls.Add(this.cbCategoryName);
this.tpUpdate.Controls.Add(this.btnUpdate);
resources.ApplyResources(this.tpUpdate, "tpUpdate");
this.tpUpdate.Name = "tpUpdate";
//
// Label9
//
resources.ApplyResources(this.Label9, "Label9");
this.Label9.ForeColor = System.Drawing.Color.Blue;
this.Label9.Name = "Label9";
//
// Label2
//
resources.ApplyResources(this.Label2, "Label2");
this.Label2.Name = "Label2";
//
// Label3
//
resources.ApplyResources(this.Label3, "Label3");
this.Label3.Name = "Label3";
//
// txtUpdateDescription
//
resources.ApplyResources(this.txtUpdateDescription, "txtUpdateDescription");
this.txtUpdateDescription.Name = "txtUpdateDescription";
//
// cbCategoryName
//
resources.ApplyResources(this.cbCategoryName, "cbCategoryName");
this.cbCategoryName.Name = "cbCategoryName";
this.cbCategoryName.SelectedIndexChanged += new System.EventHandler(this.cbCategoryName_SelectedIndexChanged);
//
// btnUpdate
//
resources.ApplyResources(this.btnUpdate, "btnUpdate");
this.btnUpdate.Name = "btnUpdate";
this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
//
// tpDatasetExample
//
this.tpDatasetExample.Controls.Add(this.Label10);
this.tpDatasetExample.Controls.Add(this.btnDataset);
this.tpDatasetExample.Controls.Add(this.dgMain);
resources.ApplyResources(this.tpDatasetExample, "tpDatasetExample");
this.tpDatasetExample.Name = "tpDatasetExample";
//
// Label10
//
resources.ApplyResources(this.Label10, "Label10");
this.Label10.ForeColor = System.Drawing.Color.Blue;
this.Label10.Name = "Label10";
//
// btnDataset
//
resources.ApplyResources(this.btnDataset, "btnDataset");
this.btnDataset.Name = "btnDataset";
this.btnDataset.Click += new System.EventHandler(this.btnDataset_Click);
//
// dgMain
//
resources.ApplyResources(this.dgMain, "dgMain");
this.dgMain.DataMember = "";
this.dgMain.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgMain.Name = "dgMain";
this.dgMain.ReadOnly = true;
//
// frmMain
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.tcMain);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Menu = this.mnuMain;
this.Name = "frmMain";
this.tcMain.ResumeLayout(false);
this.tpRecordNavigation.ResumeLayout(false);
this.tpRecordNavigation.PerformLayout();
this.tpInsert.ResumeLayout(false);
this.tpInsert.PerformLayout();
this.tpUpdate.ResumeLayout(false);
this.tpUpdate.PerformLayout();
this.tpDatasetExample.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dgMain)).EndInit();
this.ResumeLayout(false);
}
#endregion
#region " Standard Menu Code "
// This code simply shows the About form.
private void mnuAbout_Click(object sender, System.EventArgs e)
{
// Open the About form in Dialog Mode
frmAbout frm = new frmAbout();
frm.ShowDialog(this);
frm.Dispose();
}
// This code will close the form.
private void mnuExit_Click(object sender, System.EventArgs e)
{
// Close the current form
this.Close();
}
#endregion
private void btnDataset_Click(object sender, System.EventArgs e)
{
// An ADO 2.6 connection and recordset are created to pull back
// data using a SELECT statement. A data adapter and dataset are
// created. The data Adapters fill method is used to populate
// the dataset with the data in the ADO 2.6 recordset.
// The dataset is then assigned to the data grid control.
object ra = null;
string strSQL = "SELECT CustomerID, " + " CompanyName, " + " ContactName, " + " COuntry, " + " Region, " + " Phone, " + " Fax " + "FROM Customers";
rs = cnn.Execute(strSQL,out ra,0);
// Create Dataset and data adapter objects
DataSet ds = new DataSet("Recordset");
OleDbDataAdapter da = new OleDbDataAdapter();
// Call data adapter's Fill method to fill data from ADO
// Recordset to ADO.NET dataset
da.Fill(ds, rs, "Customers");
// Assign data set to grid control
dgMain.DataSource = ds;
dgMain.DataMember = "Customers";
}
private void btnFirst_Click(object sender, System.EventArgs e)
{
rs.MoveFirst();
PopulateSimpleNavigationForm();
}
private void btnLast_Click(object sender, System.EventArgs e)
{
rs.MoveLast();
PopulateSimpleNavigationForm();
}
private void btnNext_Click(object sender, System.EventArgs e)
{
// this code is used to prevent going to EOF
if (!rs.EOF) {
rs.MoveNext();
if (rs.EOF) {
rs.MovePrevious();
}
PopulateSimpleNavigationForm();
}
}
private void btnPrev_Click(object sender, System.EventArgs e)
{
// this code is used to prevent going to BOF
if (!rs.BOF) {
rs.MovePrevious();
if (rs.BOF) {
rs.MoveNext();
}
PopulateSimpleNavigationForm();
}
}
private void btnInsert_Click(object sender, System.EventArgs e)
{
// This event will insert a new record into the Categories table
// Validate form
if ((txtCategoryName.Text == "") || (txtDescription.Text == "")) {
MessageBox.Show("Please fill in all the text boxes.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
Object recordsEffected;
string strSQL = "INSERT INTO Categories(CategoryName, Description) " + "VALUES ('" + txtCategoryName.Text + "','" + txtDescription.Text + "')";
// Execute SQL statement
cnn.Execute(strSQL, out recordsEffected, 0);
if (Convert.ToInt32(recordsEffected) == 1) {
MessageBox.Show("Insert Successful!", this.Text, MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
}
private void btnUpdate_Click(object sender, System.EventArgs e)
{
// This event updates the description field of the categories
// table with the value in the description text box
if (txtUpdateDescription.Text == "")
{
MessageBox.Show("Please fill in description text box.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
string strSQL = "UPDATE Categories SET Description = " + "'" + txtUpdateDescription.Text + "' " + "WHERE CategoryName = " + "'" + cbCategoryName.Text + "'";
cm.ActiveConnection = cnn;
cm.CommandText = strSQL;
Object recordsEffected;
Object parameters = 0;
cm.Execute(out recordsEffected, ref parameters,0);
// Check to see if 1 record was effected
if (Convert.ToInt32(recordsEffected) > 0)
{
MessageBox.Show("Update Successful!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
MessageBox.Show("Update Failed!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void cbCategoryName_SelectedIndexChanged(object sender, System.EventArgs e)
{
// This event controls what heppens when a category is selected
// on the Update example.
// When a category is selected the description is displayed
// in the test box so the user can change it.
string strSQL = "SELECT Description " + "FROM Categories " + "WHERE CategoryName = '" + cbCategoryName.Text + "'";
rs.ActiveConnection = cnn;
rs.CursorType = CursorTypeEnum.adOpenStatic;
rs.Open(strSQL,cnn,ADODB.CursorTypeEnum.adOpenDynamic,ADODB.LockTypeEnum.adLockOptimistic,0);
// Set the text box to the value in the result
txtUpdateDescription.Text = Convert.ToString(rs.Fields["Description"].Value);
rs.Close();
}
private void tcMain_SelectedIndexChanged(object sender, System.EventArgs e)
{
// Close recordset if tab is changed
if (rs.State == 1)
{
rs.Close();
}
// Run init subs for sertain tabs when they are selected
switch( tcMain.SelectedIndex )
{
case 0:
InitRecordNavigation();
break;
case 2:
InitSimpleUpdate();
break;
}
}
private void InitRecordNavigation()
{
// Simple code showing how to connect to a database
// using ADO 2.6 and navigate a recordset
frmStatus frmStatusMessage = new frmStatus();
if (!HasConnected)
{
frmStatusMessage.Show("Connecting to SQL Server");
// Attempt to connect to SQL server or MSDE
bool IsConnecting = true;
while (IsConnecting)
{
try {
// Open a Connection
cnn.ConnectionTimeout = 5;
cnn.Open(Connectionstring, null,null,0);
if (cnn.State != 1)
{
throw new System.Exception("Connection failed.");
}
if (!HasConnected)
{
frmStatusMessage.Close();
}
IsConnecting = false;
HasConnected = true;
}
catch
{
if (Connectionstring == SQL_CONNECTION_STRING)
{
// Couldn't connect to SQL server. Now try MSDE
Connectionstring = MSDE_CONNECTION_STRING;
frmStatusMessage.Show("Connecting to MSDE");
}
else
{
// Unable to connect to SQL Server or MSDE
frmStatusMessage.Close();
MessageBox.Show("To run this sample you must have SQL Server ot MSDE with the Northwind database installed. For instructions on installing MSDE, view the Readme file." + MessageBoxIcon.Warning + "SQL Server/MSDE not found");
// Quit program if neither connection method was successful.
Application.Exit();
}
}
}
}
// Build SQL statement.
string strSQL = "SELECT CompanyName, " + " ContactName, " + " Phone " + "FROM Customers";
rs.ActiveConnection = cnn;
rs.CursorType = CursorTypeEnum.adOpenStatic;
rs.Open(strSQL,cnn,ADODB.CursorTypeEnum.adOpenDynamic,ADODB.LockTypeEnum.adLockOptimistic,0);
rs.MoveFirst();
}
private void InitSimpleUpdate()
{
// Populate Combo box with categories
string strSQL = "SELECT CategoryName " + "FROM Categories";
rs.ActiveConnection = cnn;
rs.CursorType = CursorTypeEnum.adOpenStatic;
rs.Open(strSQL,cnn,ADODB.CursorTypeEnum.adOpenDynamic,ADODB.LockTypeEnum.adLockOptimistic,0);
// Loop through records and add them to the combo box
while (!rs.EOF)
{
cbCategoryName.Items.Add(rs.Fields["CategoryName"].Value);
rs.MoveNext();
}
rs.Close();
cbCategoryName.SelectedIndex = 0;
}
private void PopulateSimpleNavigationForm()
{
// Populate form with data from recordset
txtCompanyName.Text = Convert.ToString(rs.Fields["CompanyName"].Value);
txtContactName.Text = Convert.ToString(rs.Fields["ContactName"].Value);
txtPhone.Text = Convert.ToString(rs.Fields["Phone"].Value);
}
I have attached UI snapshots of it to know how it looks.
