0% found this document useful (0 votes)
2 views

UNIT4 Database Programming With ADO

The document provides an overview of ADO.NET, detailing its components, architecture, and functionalities for database programming using C#. It covers topics such as connected and disconnected data access, the use of DataSets, DataTables, and commands for executing SQL statements. Additionally, it includes practical examples for inserting, updating, and retrieving data from various data sources.

Uploaded by

vivekkanet11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

UNIT4 Database Programming With ADO

The document provides an overview of ADO.NET, detailing its components, architecture, and functionalities for database programming using C#. It covers topics such as connected and disconnected data access, the use of DataSets, DataTables, and commands for executing SQL statements. Additionally, it includes practical examples for inserting, updating, and retrieving data from various data sources.

Uploaded by

vivekkanet11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Programming Using C#.

NET BCA/IT - 4th SSSDIIT - College

UNIT4: Database Programming with ADO.NET


Click to Learn

How to Display Data inside a GridView

How to Insert Data Inside Database Using SQLServer

Insert and fetch Data with Database

How to Remove Records from DataBase

Update Records From DataBase

Login Example Using DataBase

How to Store Image Using DataBase

First Next Last Previous (Navigation) Using DataBase

DataBase Connectivity With M.S Access

Country State City With DataBase Connectivity

Change Password Example

Forgot Password Example

Insert Data Using OOP

How to Merge (Join) Table Using DataBase

Save and Display Image From DataBase

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 1


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

Introduction of ADO.NET
ADO is a rich set classes, interface, structures, and enumerated types that manage
data access from different types of data stores.

There are many data access technologies available to ADO.NET

Open database Connectivity (ODBC)


Data Access Object (DAO)
Remote data Objects (RDO)
Active X Data Objects (ADO)

Q.1 Write a note on ADO.NET.


ADO.NET stands for ActiveX Data Objects.
ADO.NET provides a bridge between the front end controls and the back end
database.
ADO.NET is a set of classes that allows you to connect and work with data
sources like databases, excel file, access file, xml file, mysql, sql or notepad.
The ADO.NET Framework supports two models of Data Access Architecture,
Connection Oriented Data Access Architecture and Disconnected Data Access
Architecture.

There are 4 Core Components of .Net Data Providers that is used to connect, access and
retrieve data from the database.

1. Connection – This component is used for connecting to the database. The base class
is DbConnection.

2. Command – This component executes SQL query against the data source. The base
class is DbCommand.

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 2


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

3. DataReader – It reads data from data source. It accesses data read-only and forward-
only. The base class is DbDataReader.

4. DataAdapter – It invokes dataset and resolves updates with the data source. The
base class is DbDataAdapter.

Q.2 Explain Connected and disconnected data Architecture.


Connected Architecture

The architecture, in which connection must be opened to access the data


retrieved from database is called as connected architecture. Connected
architecture was built on the classes connection, command, datareader and
transaction.
DataReader is Connected Architecture since it keeps the connection open until
all rows are fetched one by one

Disconnected Architecture

The architecture of ADO.net in which data retrieved from database can be


accessed even when connection to database was closed is called as disconnected
architecture. Disconnected architecture of ADO.net was built on classes
connection, dataadapter, commandbuilder and dataset and dataview.
Disconnected architecture is a method of retrieving a record set from the
database and storing it giving you the ability to do many CRUD (Create, Read,
Update and Delete)
A method of using disconnected architecture is using a Dataset.
DataSet is DisConnected Architecture since all the records are brought at once
and there is no need to keep the connection alive

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 3


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

Q.3 What is difference between Connected and Disconnected


Architecture

Difference between Connected and disconnected architecture

Connected Disconnected
It is connection oriented. It is dis_connection oriented.
Datareader DataSet
Connected methods gives faster Disconnected get low in speed and
performance performance.
connected can hold the data of single table disconnected can hold multiple tables of
data
connected you need to use a read only disconnected you cannot
forward only data reader
Data Reader can't persist the data Data Set can persist the data
It is Read only, we can't update the data. We can update data

Q.4 Explain ADO.NET Components.

Connection Object

Connection Object is used for connecting your application to data source or database. It
carries required authentic information like username and password in the connection
string and opens a connection. You need to different type of connection object for
different type of data providers. For example:

OLE DB (Object Linking and Embedding, Database)– OleDbConnection


SQL Server – SqlConnection
ODBC(Open Database Connectivity) – OdbcConnection
Oracle – OracleConnection

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 4


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

Connection String

Connection String combines all the required authentic information that is used for
connecting to a Data Source, like Server Name, Database Name, User Name, Password
etc. It is just a single line string that is used by connection object to connect to the
database.

Example:

SqlConnection con = new SqlConnection("Data Source=.\SQLEXPRESS;Initial


Catalog=AVADHTUTOR;User ID=ripal;Password=pandya;Pooling=False"; );
con.Open();
// Update, Insert Delete Job in Table
con.Close();

DataReaders

The DataReader object in C# ADO.NET allows you to retrieve data from database in read-only
and forward-only mode. It means you can only read and display data but can’t update or delete
data. If you want to make modification in retrieved data you need to use DataAdapter instead of
DataReader.

Properties
PROPERTY DESCRIPTION

Depth Indicates the depth of nesting for row

FieldCount Returns number of columns in a row

IsClosed Indicates whether a data reader is closed

Item Gets the value of a column in native


format
RecordsAffec Number of row affected after a
ted transaction

Methods
METHOD DESCRIPTION
Close Closes a DataRaeder object.
Read Reads next record in the data reader.
NextResult Advances the data reader to the next result during batch transactions.
Getxxx There are dozens of Getxxx methods. These methods read a specific data type value
from a column. For example. GetChar will return a column value as a character and
GetString as a string.

DataAdapters
DataAdapters are used for controlling Datasets and it provides communication between DataSets
and DataSource. DataAdapters make a connection with Data Source and then Fill Data to
DataSets. It also Updates Data Source with DataSets.

Properties:

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 5


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

Properties Description
DeleteCommand It is used for Deleting Records from DataSource
InsertCommand It is used for adding New Record to a DataSource
SelectCommand It is used for Selecting Records from a DataSource
UpdateCommand It is used for Updating Records in a DataSource.
TableMapping It is used for mapping actual database tables and datasets.

Methods:

Method Description
Fill This method Fills Records from DataAdapters to DataSets.
Update This method update DataSource with DataSets.

DataSet

 In a simple word, A DataSet is a local copy of your Database Table


 A DataSet behaves like real Database and it represents a complete set of data that
includes tables, constraints, and relationships among the tables.
 Using the DataAdapters you can fill DataSet and use this dataset for retrieving
and storing information. When all the tasks get completed, update Real Database
with datasets.

Command

The Command Object in ADO.NET executes SQL statements and Stored


Procedures against the data source specified in the C# Connection Object.
After the execution of the SQl statement, the Command Object will return a result
set . We can retrieve the result set using a Data Reader .
The Command Object has a property called CommandText , which contains a
String value that represents the command that will be executed against the Data
Source like select, insert, delete update etc.
When the CommandType property is set to StoredProcedure, the CommandText
property should be set to the name of the stored procedure.

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 6


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

Methods of Command Object:


o ExecuteNonQuery()
 It is one of the most frequently used method in SqlCommand
Object, and is used for executing statements that do not return
result sets (ie. statements like insert data , update data etc.) .
 Example:
o cnn.Open();
o sql = "Your SQL Statemnt Here";
o cmd = new SqlCommand(sql, cnn);
o cmd.ExecuteNonQuery();
o ExecuteReader()
 The SqlDataReader Object is a stream-based , forward-only, read-
only retrieval of query results from the Data Source, which do not
update the data it contains.
 it will instantiate a SqlClient.SqlDataReader Object.
 Example:
o cnn.Open();
o cmd = new SqlCommand(sql, cnn);
o reader=cmd.ExecuteReader();
o ExecuteScaler()

it returns first column of the first row in the result set return by the query.
It’s used Select Query with Aggregate Function(sum,count).

Q.5 Explain DataSet,DataTable,DataRow,DataColumn,DataView?

Dataset
It persists data in memory which is separately from the database.
By nature it is disconnected.
You can perform all DML statement.
You can load data in dataset from any data source like SQL Server, Oracle etc.
You can create table inside the Dataset even you can define the keys and create
relationship between them.
It belongs to “System.Data” namespace.

How to Declare Dataset in C#

Using system.Data;
DataSet objDS = new DataSet();

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 7


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

How Dataset Work:

DataSet DataTable Collection

Data Relation

DataColumn DataRow Constraints

DataTable

DataTable is the collection of tables.


The following syntax is used for a DataTable:
<DataSet>.Tables[Index]/[Name]
For example:
Ds.Tables[0] Or Ds.tables[“Company”]

Every DataTable is again a collection of Rows and Columns where each row is
represented as a DataRow class and identified by its index position.

Each column is represented as a DataColumn class and identified by index


position or name.
DataRow
It is a collection rows.
Syntax:
<datatable>.Rows[Index].
For examle:
Ds.tables[0].rows[0]

DataColumns

It is a collection Columns.
Syntax:
<datatable>.Columns[Index] OR columns[Name]
For example:
Ds.Tables[0].Columns[0] Or: Ds.Tables[0].Columns[“ENO”]

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 8


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

Ds.tables[0].rows[0]
DataColumn

The DataColumn is the fundamental building block for creating the schema of a DataTable.
Each DataColumn has a DataType property that determines the kind of data the column
holds.
You can simple – bind a control to column within a data table.
For example, you can restrict the data type to integers, or strings, or decimals. Because data
that is contained by the DataTable is typically merged back into its original data source, you
must match the data types to those in the data source.
This class provides the following Properties.
Property Description
AllowDBNull Gets or sets a value that indicates whether null values are
allowed in this column for rows that belong to the table.
AutoIncrement Gets or sets a value that indicates whether the column
automatically increments the value of the column for new
rows added to the table.
ColumnName Gets or sets the name of the column in
the DataColumnCollection.
DataType Gets or sets the type of data stored in the column.
ReadOnly Gets or sets a value that indicates whether the column
allows for changes as soon as a row has been added to
the table.
Unique Gets or sets a value that indicates whether the values in
each row of the column must be unique.

This class provides the following methods.


Method Description
CheckNotAllowNull() This member supports .NET infrastructure and is not
intended to be used directly from your code.
CheckUnique() This member supports .NET infrastructure and is not
intended to be used directly from your code.
Equals(Object) Determines whether the specified object is equal to the
current object.
Example

// Create a new DataTable.


DataTable table = new DataTable("ParentTable");
// Declare variables for DataColumn and DataRow objects.
DataColumn column;
DataRow row;
// Create new DataColumn, set DataType, ColumnName and add to DataTable.
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
column.ReadOnly = true;
column.Unique = true;
column.AutoIncrement = false;

// Add the Column to the DataColumnCollection.


table.Columns.Add(column);

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 9


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

// Instantiate the DataSet variable.


DataSet dataSet = new DataSet();
// Add the new DataTable to the DataSet.
dataSet.Tables.Add(table);
// Create three new DataRow objects and add
// them to the DataTable
for (int i = 0; i<= 2; i++)
{
row = table.NewRow();
row["id"] = i;
table.Rows.Add(row);
}
DataRow

The DataRow and DataColumn objects are primary components of a DataTable.


Use the DataRow object and its properties and methods to retrieve and evaluate; and insert,
delete, and update the values in the DataTable.
The DataRowCollection represents the actual DataRow objects in the DataTable.
To create a new DataRow, use the NewRow method of the DataTable object. After creating a
new DataRow, use the Add method to add the new DataRow to the DataRowCollection.
You can delete a DataRow from the DataRowCollection by calling the Remove method of
the DataRowCollection, or by calling the Delete method of the DataRow object.
This class provides the following Properties.
Property Description
Item Represents an item of a row
ItemArray Represents all values in a row.
RowState Indicates the current state of a row.
Table Returns the DataTable to which this row is
attached.

This class provides the following methods.


Method Description
AcceptChanges Comments all the changes made to this row
BeginEdit Starts an edit operation on a row
CancelEdit Cancels the current edit on a row
Delete Deletes a DataRow
EndEdit Ends the current edit on a row
GetChildRows Returns child rows of a DataRow
GetParentRows Returns parent rows of a DataRow
RejectsChanges Rejects all the changes made since last AcceptChanges
Example

DataTable dt = new DataTable();


DataRow dr;
// Create new DataRow objects and add to DataTable.
for(int i = 0; i < 10; i++)
{
dr = table.NewRow();
dr["id"] = i;
dr["item"] = "item " + i.ToString();
dt.Rows.Add(dr);
}

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 10


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

DataRelation
A DataRelation is used to relate two DataTable objects to each other
through DataColumn objects. For example, in a Customer/Orders relationship, the
Customers table is the parent and the Orders table is the child of the relationship. This is
similar to a primary key/foreign key relationship.
Relationships are created between matching columns in the parent and child tables. That is,
the DataType value for both columns must be identical.
This class provides the following Properties.
Property Description
ChildColumns Gets the child DataColumn objects of this relation.
ChildKeyConstraint Gets the ForeignKeyConstraint for the relation.
ChildTable Gets the child table of this relation.
ParentColumns Gets an array of DataColumn objects that are the parent columns of
this DataRelation.
ParentKeyConstraint Gets the UniqueConstraint that guarantees that values in the parent
column of a DataRelation are unique.
ParentTable Gets the parent DataTable of this DataRelation.
RelationName Gets or sets the name used to retrieve a DataRelation from
the DataRelationCollection.

This class provides the following methods.


Method Description
Equals(Object) Determines whether the specified object is equal to the
current object.
GetType() Gets the Type of the current instance.

Example

private void CreateRelation()


{
// Get the DataColumn objects from two DataTable objects
// in a DataSet. Code to get the DataSet not shown here.
DataColumn parentColumn =
DataSet1.Tables["Customers"].Columns["CustID"];
DataColumn childColumn =
DataSet1.Tables["Orders"].Columns["CustID"];
// Create DataRelation.
DataRelation relCustOrder;
relCustOrder = new DataRelation("CustomersOrders",
parentColumn, childColumn);
// Add the relation to the DataSet.
DataSet1.Relations.Add(relCustOrder);
}
DataView
DataView works with the DataTable. Every DataTable has a default DataView.
With the help of DataView you can create different views of the data stored in a DataTable, a
capability that is often used in data-binding application.
Using a DataView, you can expose the data in a table with different sort orders and filter
data.

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 11


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

A DataView provides you with a dynamic view of a single set of data to which you can apply
different sorting and filtering criteria, similar to the view provided by any database
software.
This class provides the following Properties.
Property Description
AllowDelete Gets or sets a value that indicates whether deletes are
allowed.
AllowEdit Gets or sets a value that indicates whether edits are
allowed.
AllowNew Gets or sets a value that indicates whether the new rows
can be added by using the AddNew() method.
RowFilter Gets or sets the expression used to filter which rows are
viewed in the DataView.
Sort Gets or sets the sort column or columns, and sort order
for the DataView.

This class provides the following methods.


Method Description
AddNew() Adds a new row to the DataView
CopyTo(Array, Int32) Copies items into an array. Only for Web Forms
Interfaces.
FindRows(Object) Returns an array of DataRowView objects whose
columns match the specified sort key value.

Example

The following Code creates a view that includes all rows with a null value in the Country field
and then deletes them:

// Find all the rows where a country is not specified


DataView view = new DataView (ds.Tables [“Customers”]);
view.RowFilter = “Country is NULL”;
// Delete these rows.
foreach (DataRowView row in view)
{
row.Delete();
}
//Display the result
dataGrid1.DataSource = ds.Table[“Customer”]. DefaultView;
This example uses the indexer for the DataView, which accesses the collection of
DataRowView objects.
Each DataRowView represents a single row from the original DataTable.
The DataRowView provides most of the features as the underlying DataRow object,
including the ability to begin and end editing, access values using the field name, and delete
the row.

Data Binding

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 12


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

Data binding is the process that establishes a connection between the app UI and the data it
displays. If the binding has the correct settings and the data provides the proper
notifications, when the data changes its value, the elements that are bound to the data
reflect changes automatically.
For example, if the user edits the value in a TextBox element, the underlying data value is
automatically updated to reflect that change.

As the figure shows, data binding is essentially the bridge between your binding target and
your binding source. The figure demonstrates the following fundamental WPF data binding
concepts:
Typically, each binding has four components:
o A binding target object.
o A target property.
o A binding source.
o A path to the value in the binding source to use.
For example, if you bound the content of a TextBox to the Employee.Name property, you
would set up your binding like the following table:

Setting Value
Target TextBox
Target property Text
Source object Employee
Source object value path Name

Example

SqlConnection con = new SqlConnection(“<Connection String>”);


con.Open( );
SqlDataAdapter da = new SqlDataAdapter (“Select fn,ln,city from emp”,con);
DataSet ds = new DataSet( );
da.fill (ds,“emp”);
textBox1.DataBindings.Add(“Text”, ds, “FN”);
textBox2.DataBindings.Add(“Text”, ds, “LN”);
textBox3.DataBindings.Add(“Text”, ds, “CITY”);

Q.6 Explain Data Providers in ADO.NET

Data provider is used to connect to the database, execute commands and retrieve the
record. It is lightweight component with better performance. It also allows us to place
the data into DataSet to use it further in our application.

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 13


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

The .NET Framework provides the following data providers that we can use in our
application.

.NET Framework data Description


provider
.NET Framework Data It provides data access for Microsoft SQL Server. It requires the
Provider for SQL Server System.Data.SqlClient namespace.
.NET Framework Data It is used to connect with OLE DB. It requires the System.Data.OleDb
Provider for OLE DB namespace.
.NET Framework Data It is used to connect to data sources by using ODBC. It requires the
Provider for ODBC System.Data.Odbc namespace.
.NET Framework Data It is used for Oracle data sources. It uses the
Provider for Oracle System.Data.OracleClient namespace.
EntityClient Provider It provides data access for Entity Data Model applications. It
requires the System.Data.EntityClient namespace.
.NET Framework Data It provides data access for Microsoft SQL Server Compact 4.0. It
Provider for SQL Server requires the System.Data.SqlServerCe namespace.
Compact 4.0.

Exercise 1. Performing operation like insert,edit,delete,search on


table student(rno,name,city,contact) using Disconnected architecture
Step-1: Application Designing

Enter Roll No, Name, City, Contact (textBox)

Select Name to Search (ComboBox)and Search Record (Button)

Navigation: First, Next, Last (Button)

Buttons: New , Save, Delete, Edit (Button)

Step-2: Coding

namespace data_conn
{
public partial class Form2 : Form
{
int r;
SqlConnection cn;
SqlDataAdapter da;
DataTable dt = new DataTable();
public Form2()
{
InitializeComponent();
}

private void Form2_Load(object sender, EventArgs e)


{

cn = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\avadh.mdf;Integrated Security=True;User
Instance=True");
da = new SqlDataAdapter("select * from student", cn);
dt.Clear();

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 14


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

da.Fill(dt);
r = 0;
fatchdata();
dataGridView1.DataSource = dt;
//to add name fields in combobox to search
for (int i = 0; i < dt.Rows.Count; i++)
comboBox1.Items.Add(dt.Rows[i][1].ToString());
}

public void fatchdata()


{
txtrno.Text = dt.Rows[r][0].ToString();
txtname.Text = dt.Rows[r][1].ToString();
txtcity.Text = dt.Rows[r][2].ToString();
txtcontact.Text = dt.Rows[r][3].ToString();
}

private void btnfirst_Click(object sender, EventArgs e)


{

r = 0;
fatchdata();
label4.Text = (r + 1).ToString() + " OF " + dt.Rows.Count;
}

private void btnprev_Click(object sender, EventArgs e)


{
try
{
r -= 1;
fatchdata();

label4.Text = (r + 1).ToString() + " OF " + dt.Rows.Count;


}
catch
{
MessageBox.Show("this is first record");
}
}

private void btnnext_Click(object sender, EventArgs e)


{
try
{
r += 1;
fatchdata();
}
catch
{
MessageBox.Show("this is last record");
r -= 1;
}
label4.Text = (r + 1).ToString() + " OF " + dt.Rows.Count;
}

private void btnlast_Click(object sender, EventArgs e)


{
r = dt.Rows.Count-1;
fatchdata();
label4.Text = (r + 1).ToString() + " OF " + dt.Rows.Count;
}

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 15


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

private void btnnew_Click(object sender, EventArgs e)


{
txtrno.Clear();
txtname.Clear();
txtcity.Clear();
txtcontact.Clear();
MessageBox.Show("enter data into textbox and then click on 'SAVE' button");
txtrno.Focus();
}

private void btnsave_Click(object sender, EventArgs e)


{
try
{
da = new SqlDataAdapter("insert into student(name,city,contact) values('" + txtname.Text + "','" +
txtcity.Text+"',"+ txtcontact.Text+")", cn);
da.Fill(dt);
MessageBox.Show("AVADH: record is successfully inserted");
Form2_Load(sender, e);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

private void btndelete_Click(object sender, EventArgs e)


{
try
{
da = new SqlDataAdapter("delete from student where rno="+txtrno.Text, cn);
da.Fill(dt);
MessageBox.Show("record is successfully deleted");
Form2_Load(sender, e);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

private void btnedit_Click(object sender, EventArgs e)


{
try
{
da = new SqlDataAdapter("update student set name='avadh',contact=9000123 where rno=" +
txtrno.Text , cn);
da.Fill(dt);
MessageBox.Show("record is successfully update");
Form2_Load(sender, e);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

private void btnsearch_Click(object sender, EventArgs e)


{

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 16


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

try
{
da = new SqlDataAdapter("select * from student where name='" + comboBox1.Text + "'", cn);
dt.Clear();
da.Fill(dt);
txtrno.Text = dt.Rows[0][0].ToString();
txtname.Text = dt.Rows[0][1].ToString();
txtcity.Text = dt.Rows[0][2].ToString();
txtcontact.Text = dt.Rows[0][3].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

Exercise 2. Performing operation like insert,edit,delete,search on


table student(rno,name,city,contact) using Connected architecture
Step-1: application Designing

Enter Roll No, Name, City, Contact (textBox)

Select Name to Search (ComboBox)and Search Record (Button)

Navigation: First, Next, Last (Button)

Buttons: New , Save, Delete, Edit (Button)

Step-2: Coding
namespace data_conn
{
public partial class Form3 : Form
{
SqlConnection cn;
SqlCommand cmd;
SqlDataReader dr;
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
cn = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\avadhtutor.mdf;Integrated Security=True;User
Instance=True");
cn.Open();
cmd = new SqlCommand("select * from student",cn);
dr = cmd.ExecuteReader();
dr.Read();
fatchdata();
}
private void fatchdata()
{

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 17


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

txtrno.Text = dr.GetValue(0).ToString();
txtname.Text = dr.GetValue(1).ToString();
txtcity.Text = dr.GetValue(2).ToString();
txtcontact.Text = dr.GetValue(3).ToString();
}

private void btnnext_Click(object sender, EventArgs e)


{
try
{
dr.Read();
fatchdata();
}
catch
{
MessageBox.Show("this is last record");
} }

private void btnfirst_Click(object sender, EventArgs e)


{
dr.Close();
cmd = new SqlCommand("select * from student", cn);
dr = cmd.ExecuteReader();
dr.Read();
fatchdata();
}

private void btnlast_Click(object sender, EventArgs e)


{
while (dr.Read())
{
fatchdata();
} }
private void btnnew_Click(object sender, EventArgs e)
{
txtname.Clear();
txtcity.Clear();
txtcontact.Clear();
MessageBox.Show("AvadhTutor: enter values to textboxes then click on Save");
txtname.Focus();
}

private void btnsave_Click(object sender, EventArgs e)


{
dr.Close();
try
{
cmd=new SqlCommand("insert into
student(name,city,contact)values('"+txtname.Text+"','"+txtcity.Text+"',"+txtcontact.Text+")",cn);
cmd.ExecuteNonQuery();
MessageBox.Show("record inserted");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

private void btndelete_Click(object sender, EventArgs e)


{
dr.Close();
try

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 18


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

{
cmd = new SqlCommand("delete from student where name='"+txtname.Text+"'",cn);
cmd.ExecuteNonQuery();
MessageBox.Show("record deleted");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

private void btnedit_Click(object sender, EventArgs e)


{
dr.Close();
cmd = new SqlCommand("update student set name='"+txtname.Text+"',city='"+txtcity.Text+"',contact="+
txtcontact.Text +" where rno=" + txtrno.Text,cn);
cmd.ExecuteNonQuery();
MessageBox.Show("record updated");
}

private void btnsearch_Click(object sender, EventArgs e)


{
try
{
dr.Close();
cmd = new SqlCommand("select * from student where name='Ripal'", cn);
dr = cmd.ExecuteReader();
dr.Read();
fatchdata();

}
catch
{
MessageBox.Show("record not found");
}
}
}
}

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 19


Programming Using C#.NET BCA/IT - 4th SSSDIIT - College

Learn All Programming From


Youtube.com/avadhtutor

C Sharp All Videos


https://www.youtube.com/watch?v=YoA-D_tkVbo&list=PLkx9f4H3tJMLLOfG81ywgpTEJqEg-
sXlz

Blog
pandyaripal.blogspot.com

instagram
instagram.com/avadhtutor

Prepared By: Ripal Pandya | Youtube.com/avadhtutor | instagram.com/avadhtutor Page 20

You might also like