0% found this document useful (0 votes)
3 views21 pages

Lecture_10 (Working with DB_2)

The document outlines the objectives and examples of using ADO.NET's disconnected object model to manage data in local memory. It provides code examples for connecting to different database types, performing CRUD operations, and handling data in a Windows Forms application. The document includes specific implementations for Microsoft Access and SQL Server databases.

Uploaded by

Ahmed Al-nasheri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

Lecture_10 (Working with DB_2)

The document outlines the objectives and examples of using ADO.NET's disconnected object model to manage data in local memory. It provides code examples for connecting to different database types, performing CRUD operations, and handling data in a Windows Forms application. The document includes specific implementations for Microsoft Access and SQL Server databases.

Uploaded by

Ahmed Al-nasheri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Dr.

Ahmed Alnasheri
Objectives
To use ADO.NET's disconnected object model to store

data from a database in local memory.

Practicing ADO by using some examples.

2
Programming with ADO
 Providers: In last lecture, we mentioned that we can use
ADO in two different ways:
 Use ADO to connect to the data base directly, or
 Use ADO disconnected object to load data into memory

 In the second case we use various providers

 Provider=Microsoft.Jet.OLEDB.4.0; MSACCESS 2003 (.MDB)


 Provider=Microsoft.ACE.OLEDB.12.0; MSACCESS 2007 (.accDB)
 Provider=SqlOLEDB; SQL Server DB (.mdf)

 The used database should be found in the \bin\Debug of your


application.
3
Example 1 (Data Source=BOOKS.mdb)

4
Example 1
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;
 using System.Data.OleDb;

 namespace InsertUpdateDeleteDemoDB
 {
 public partial class Form1 : Form
 {
 private const string conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BOOKS.mdb;";
 readonly OleDbConnection con = new OleDbConnection(conString);
 OleDbCommand cmd;
 OleDbDataAdapter adapter;
 readonly DataTable dt = new DataTable();

5
Example 1
 public Form1()
 {
 InitializeComponent();

 dataGridView1.ColumnCount = 3;
 dataGridView1.Columns[0].Name = "ID";
 dataGridView1.Columns[1].Name = "Name";
 dataGridView1.Columns[2].Name = "State";


 //SELECTION MODE
 dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
 dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
 dataGridView1.MultiSelect = false;
 }

 private void populate(string id, string name, string state)


 {
 dataGridView1.Rows.Add(id, name, state);
 }

6
Example 1
 private void retrieve()
 {
 dataGridView1.Rows.Clear();
 //SQL STATEMENT
 String sql = "SELECT * FROM tbl_Record order by ID";
 cmd = new OleDbCommand(sql, con);
 try
 {
 con.Open();
 adapter = new OleDbDataAdapter(cmd);
 adapter.Fill(dt);
 //LOOP THROUGH DATATABLE
 foreach (DataRow row in dt.Rows)
 {
 populate(row[0].ToString(), row[1].ToString(), row[2].ToString());
 }

 con.Close();
 //CLEAR DATATABLE
 dt.Rows.Clear();
 }
 catch (Exception ex)
 {
 MessageBox.Show(ex.Message);
 con.Close();
 }
 }

7
Example 1
 private void clearTxts()
 {
 txt_Name.Text = "";
 txt_State.Text = "";
 txt_ID.Text = "";
 }

 private void btn_Insert_Click(object sender, EventArgs e)


 {
 const string sql = "INSERT INTO tbl_Record(ID,Name,State) VALUES(@ID,@Name,@State)";
 cmd = new OleDbCommand(sql, con);
 //ADD PARAMS
 cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(txt_ID.Text));
 cmd.Parameters.AddWithValue("@NAME", txt_Name.Text);
 cmd.Parameters.AddWithValue("@STATE", txt_State.Text);

 //OPEN CON AND EXEC INSERT
 try
 {
 con.Open();
 if (cmd.ExecuteNonQuery() > 0)
 {
 clearTxts();
 MessageBox.Show(@"Successfully Inserted");
 }
 con.Close();
 retrieve();
 }
 catch (Exception ex)
 {
 MessageBox.Show(ex.Message);
 con.Close();
 }
 }

8
Example 1
 private void btn_Update_Click(object sender, EventArgs e)
 {
 string sql = "UPDATE tbl_Record SET Name='" + txt_Name.Text + "',State ='" + txt_State.Text + "' WHERE ID=" + txt_ID.Text + "";
 cmd = new OleDbCommand(sql, con);

 //OPEN CONNECTION,UPDATE,RETRIEVE DATAGRIDVIEW


 try
 {
 con.Open();
 adapter = new OleDbDataAdapter(cmd)
 {
 UpdateCommand = con.CreateCommand()
 };
 adapter.UpdateCommand.CommandText = sql;
 if (adapter.UpdateCommand.ExecuteNonQuery() > 0)
 {
 clearTxts();
 MessageBox.Show(@"Successfully Updated");
 }
 con.Close();

 //REFRESH DATA
 retrieve();
 }
 catch (Exception ex)
 {
 MessageBox.Show(ex.Message);
 con.Close();
 }
 }

9
Example 1
 private void btn_Delete_Click(object sender, EventArgs e)
 {
 String sql = "DELETE FROM tbl_record WHERE ID=" + txt_ID.Text + "";
 cmd = new OleDbCommand(sql, con);

 //'OPEN CONNECTION,EXECUTE DELETE,CLOSE CONNECTION


 try
 {
 con.Open();
 adapter = new OleDbDataAdapter(cmd);
 adapter.DeleteCommand = con.CreateCommand();
 adapter.DeleteCommand.CommandText = sql;

 //PROMPT FOR CONFIRMATION BEFORE DELETING


 if (MessageBox.Show(@"Are you sure to permanently delete this?", @"DELETE", MessageBoxButtons.OKCancel,
MessageBoxIcon.Warning) == DialogResult.OK)
 {
 if (cmd.ExecuteNonQuery() > 0)
 {
 MessageBox.Show(@"Successfully deleted");
 }
 }
 con.Close();
 retrieve();
 }
 catch (Exception ex)
 {
 MessageBox.Show(ex.Message);
 con.Close();
 }
 }

10
Example 1
 private void btn_Clare_Click(object sender, EventArgs e)
 {
 dataGridView1.Rows.Clear();
 clearTxts();

 }

 private void btn_Retrive_Click(object sender, EventArgs e)


 {
 retrieve();

 }
 } // end Class Form1
 } // End namespace class

11
Example 2 ( Data Source = SmallPub.mdf )

12
Example 2
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;
 using System.Data.SqlClient;

 namespace WindowsFormsApplication18
 {

 public partial class Form1 : Form
 {
 string connectionString = "Data Source =
(LocalDB)\\v11.0;AttachDbFilename=C:\\csharp_prog\\database\\WindowsFormsApplication15\\WindowsFormsApplication15\\Smal
lPub.mdf;Integrated Security=True;Connect Timeout=30;";

 public Form1()
 {
 InitializeComponent();

 Bind();
 }

13
Example 2
 private void Clear()
 {
 txtCat.Text = string.Empty;
 txtDesc.Text = string.Empty;
 }

 private void Bind()


 {

 SqlConnection con = new SqlConnection(connectionString);

 con.Open();
 SqlDataAdapter da = new SqlDataAdapter("select * from Category", con);
 DataTable dt = new DataTable();
 da.Fill(dt);
 dataGridView1.DataSource = dt;
 con.Close();
 }

14
Example 2
 private void btnSave_Click(object sender, EventArgs e)
 {
 try
 {
 if (txtCat.Text != "")
 {
 SqlConnection con = new SqlConnection(connectionString);

 con.Open();
 SqlCommand cmd = new SqlCommand("Insert Into Category(Categoryid,Description) Values (@Catid,@Descr)", con);
 cmd.Parameters.AddWithValue("Catid", txtCat.Text);
 cmd.Parameters.AddWithValue("Descr", txtDesc.Text);
 cmd.ExecuteNonQuery();
 con.Close();
 MessageBox.Show("Inserted sucessfully");
 Bind();
 Clear();
 }
 else
 {
 MessageBox.Show("Category Id Can not be Empty");
 }
 }
 catch (Exception err)
 {
 MessageBox.Show("Duplicate !!!!!!");
 }

 }

15
Example 2
 private void btnEdit_Click(object sender, EventArgs e)
 {
 int i;
 i = dataGridView1.SelectedCells[0].RowIndex;
 txtCat.Text = dataGridView1.Rows[i].Cells[0].Value.ToString();
 txtDesc.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();
 txtCat.Enabled = false;
 txtDesc.Focus();
 }

 private void btnUpdate_Click(object sender, EventArgs e)


 {
 SqlConnection con = new SqlConnection(connectionString);

 con.Open();
 SqlCommand cmd = new SqlCommand("Update Category set categoryid= @Catid, Description = @Descr
Where(Categoryid=@CatID)", con);
 cmd.Parameters.AddWithValue("@CatID", txtCat.Text);
 cmd.Parameters.AddWithValue("@Descr", txtDesc.Text);

 cmd.ExecuteNonQuery();
 MessageBox.Show("updated......");
 con.Close();
 Bind();
 Clear();
 txtCat.Enabled = true;
 }

16
Example 2
 private void btnDelete_Click(object sender, EventArgs e)
 {
 SqlConnection con = new SqlConnection(connectionString);
 SqlCommand delcmd = new SqlCommand();

 int i;
 i = dataGridView1.SelectedCells[0].RowIndex;

 if (dataGridView1.Rows.Count > 1 && i != dataGridView1.Rows.Count - 1)


 {
 delcmd.CommandText = "DELETE FROM Category WHERE Categoryid=" +
dataGridView1.CurrentRow.Cells[0].Value.ToString() + "";
 con.Open();
 delcmd.Connection = con;
 delcmd.ExecuteNonQuery();
 con.Close();
 dataGridView1.Rows.RemoveAt(dataGridView1.SelectedCells[0].RowIndex);
 MessageBox.Show("Row Deleted");
 Bind();
 }
 }

 }// end of class form 1
 } // end of name space

17
Example 3 (Master Detail Form)

18
Example 2
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;

 namespace WindowsFormsApplication8
 {
 public partial class Form1 : Form
 {
 public Form1()
 {
 InitializeComponent();
 }

 private void categoryBindingNavigatorSaveItem_Click(object sender, EventArgs e)


 {
 this.Validate();
 this.categoryBindingSource.EndEdit();
 this.tableAdapterManager.UpdateAll(this.smallPubDataSet);

 }

19
Example 3
 private void Form1_Load(object sender, EventArgs e)
 {
 // TODO: This line of code loads data into the 'smallPubDataSet.Book' table. You can move, or remove it, as needed.
 this.categoryTableAdapter.Fill(this.smallPubDataSet.Category);
 this.bookTableAdapter.Fill(this.smallPubDataSet.Book, Convert.ToInt32(categoryIdTextBox.Text));
 // TODO: This line of code loads data into the 'smallPubDataSet.Category' table. You can move, or remove it, as needed.

 }

 private void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e)


 {
 this.bookTableAdapter.Fill(this.smallPubDataSet.Book, Convert.ToInt32(categoryIdTextBox.Text));
 }

 private void bindingNavigatorMoveLastItem_Click(object sender, EventArgs e)


 {
 this.bookTableAdapter.Fill(this.smallPubDataSet.Book, Convert.ToInt32(categoryIdTextBox.Text));
 }

 private void bindingNavigatorMovePreviousItem_Click(object sender, EventArgs e)


 {
 this.bookTableAdapter.Fill(this.smallPubDataSet.Book, Convert.ToInt32(categoryIdTextBox.Text));
 }

 private void bindingNavigatorMoveFirstItem_Click(object sender, EventArgs e)


 {
 this.bookTableAdapter.Fill(this.smallPubDataSet.Book, Convert.ToInt32(categoryIdTextBox.Text));
 }
 }
 }

20
The End
21

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy