Professional Documents
Culture Documents
NET Lounge
Module 5:
Information
Management Basics
Chapter 1: Table creation & Constraints
Chapter 2: Manipulating Information
Chapter 3: Aggregation of Information
Chapter 4: SQL Subquery
Chapter 5: SQL Server Joins
Chapter 6: Stored Procedures
Chapter 7: Indexes & Views
Chapter 8: ADO.NET Connected model
Chapter 9: ADO.NET Disconnected model
Example
ALTER TABLE Customer
ADD Location varchar (50);
Drop Column
Syntax
ALTER TABLE table_name
DROP COLUMN column_name
Example
ALTER TABLE Customer
Drop Location varchar (50);
Change Data Type
Syntax
ALTER TABLE table_name
ALTER COLUMN column_name datatype
Example
ALTER TABLE Customer
Drop Location varchar (30);
1.2. Constraints
Constraints helps to ensure that valid data goes into the database entity by specifying rules.
- NOT NULL: Ensures that attribute cannot be null.
- Primary Key: Represents a column or combination of columns as a unique identity for a row
- FOREIGN KEY: Used to establish relationships between tables using matching columns.
- UNIQUE: The value is unique (not repeated for other entities)
- Check: Used to allow values for a column based on a condition
- Default: Used for inserting default value into columns.
NOT NULL
The NOT NULL constraint will not allow a column to accept NULL values
Below is an example for creating NOT NULL constraint.
Create table Customer (CustomerID int NOT NULL, Name varchar (50) NOT NULL, Age int NOT
NULL, Gender varchar (10) NOT NULL, Occupation varchar (10))
Primary Key
The PRIMARY KEY constraint identifies each record in a database table by allowing only unique
values.
Each table can have only ONE primary key
Below is an example for creating Primary Key constraint.
Create table Customer (CustomerID int NOT NULL Primary Key, Name varchar (50) NOT NULL,
Age int NOT NULL, Gender varchar (10) NOT NULL, Occupation varchar (10))
Primary Key can also be added using alter statement as below
ALTER TABLE Customer
ADD PRIMARY KEY (CustomerID)
Foreign Key
Foreign Key is used to establish relationships between tables using matching columns
A FOREIGN KEY in one table refers to a PRIMARY KEY in another table.
It ensures that data available in the Primary key column of one table can only be entered in the
foreign key column of another table.
Below is an example for creating Foreign Key constraint
CREATE TABLE Orders
(
OrderId int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
CustomerId int FOREIGN KEY REFERENCES Customer (CustomerID)
)
Foreign Key can also be added using alter statement as below
ALTER TABLE Orders
ADD FOREIGN KEY (CustomerId)
REFERENCES Customer (CustomerId)
UNIQUE
UNIQUE Constraint like Primary Key ensures uniqueness for a column. The UNIQUE Constraint is
different from Primary Key in that a table can have only Primary Key but there can be many columns
with Unique Constraint.
Below is an example for creating Unique Constraint
Create table Customer (CustomerID int NOT NULL Primary Key, Name varchar (50) NOT NULL,
Age int NOT NULL, Gender varchar (10) NOT NULL, Occupation varchar (10), Contact int UNIQUE)
Check
Check constraint is used to allow values for a column based on a condition.
Below is an example for creating Check Constraint
We can create a Check Constraint on Age column to allow only values greater than 0.
Create table Customer (CustomerID int NOT NULL Primary Key, Name varchar (50) NOT NULL,
Age int NOT NULL, Gender varchar (10) NOT NULL, Occupations varchar (10), CHECK (Age >0))
Default
Default constraint is used for inserting default value into columns.
Below is an example for creating Default Constraint
We can create a Default Constraint on Location column to enter the default location as 'India' if
location is not inserted while entering Customer details.
Create table Customer (CustomerID int NOT NULL Primary Key, Name varchar (50) NOT NULL,
Age int NOT NULL, Gender varchar (10) NOT NULL, Occupations varchar (10), Location varchar
(20) DEFAULT 'India')
As we need to insert Employee details and their salary details on monthly basis we can create
one table for Employee details and one table for storing Employee Salary details
2.
Create the table Employee with Employee id, Employee name, Date of Joining, Age, Contact
number columns.
3.
Create the table Employee Salary with HRA, Basic, PF, Bonus and Gross
As the Employee Id should be unique and identify each row separately we can
We can create a Check Constraint on age and Unique Constraint on Contact in Employee
table.
3.
In Employee salary details create Salary Id as Primary Key and Employee ID as foreign key
The below example will retrieve the first name from the Customer Name in which the
First and the Last Name are separated by spaces.
Select SUBSTRING (CustomerName, 1, CHARINDEX (' ', CustomerName)) from Customer
The Char Index function returns the position of the space character in Customer
Name. Then using the Substring function we can retrieve the first name by providing the start
position and the position returned by Char Index function.
Select statement with Convert Functions
The Convert function is sued to display the date columns in the table in different styles
Syntax
SELECT CONVERT (data type, attribute1, format) FROM Table;
Example
The below statement will display the Date of Birth in mm/dd/yy format.
Select Convert (varchar (10), DOB, 101) from Customer
Select statement with Filters
Select statements with Filters are used to select records based on condition
1. SELECT statement with WHERE
The filter condition is specified using the WHERE Clause
Syntax
SELECT attribute1 FROM Table WHERE attribute2 = xyz;
SELECT attribute1 FROM Table WHERE attribute2 = xyz AND attribute3 = pqr;
Example
Select CustomerName from Customer where CustomerID > 100;
Select CustomerName from Customer where CustomerID > 100 and CustomerID < 200;
2. SELECT statement with WHERE and IN/NOT IN
This filter is used for checking for matching and unmatched records given a list of values
Syntax
SELECT attribute1 FROM Table WHERE attribute2 IN (pqr, xyz);
SELECT attribute1 FROM Table WHERE attribute2 NOT IN (pqr, xyz);
Example
Select CustomerID, CustomerName from Customer Where Location in ('India', 'US')
Displays the Customer details whose Location is either India or US.
Select CustomerID, CustomerName from Customer Where Location NOT in ('India', 'US')
Displays the Customer details whose Location is neither India nor US.
3. SELECT statement with WHERE and NULL
This filter is used for selecting records for columns with NULL value.
Syntax
SELECT attribute1 FROM Table WHERE attribute2 IS NULL;
Example
Select CustomerID, CustomerName from Customer where Location is NULL
Displays the Customer details whose Location is NULL.
4. SELECT statement with Order By
This filter is used to display the records based on column values either in ascending or descending
order
Syntax
SELECT attribute1 FROM Table ORDER BY attribute1;
SELECT attribute1 FROM Table ORDER BY attribute1 order by desc.
Example
Select CustomerID, CustomerName from Customer order by Location.
Select CustomerID, CustomerName from Customer order by Location desc
5. SELECT statement with Group By
This filter is used for grouping records based on a column value. The column values used for
grouping can be listed using the select statement.
Syntax
SELECT attribute1 FROM Table GROUP BY attribute1;
Example
SELECT Location FROM Customer GROUP BY Location;
In the above example the records in Customer table will be grouped by location values. Suppose we
have locations like India, US, UK, the records will be now grouped under US, UK and India. The
column values used for grouping alone can be displayed using Select. So the above statement will
display only US, UK and India.
6. SELECT statement with Group By and Having
The having clause is used for displaying the column values used in group by clause based on a
condition. In the above example if we want to display the locations which are having a count of more
than 10 employees, then we can go for having clause.
Having clause has to be used along with aggregate functions. Refer to Aggregate functions
documents for understanding on Aggregate functions.
Syntax
SELECT attribute1 FROM Table GROUP BY attribute1 HAVING aggregate_function (attribute1) >
value;
Example
SELECT Location FROM Customer GROUP BY Location having count (Location) > 0
The aggregate function used is the count function.
Solution
Insert into Employee (1, 'Emp1','Finance','09-09-2000')
Update Employee set EmpName ='Emp2', Department='Accounts' where Empid =2
Delete from Employee where Empid= 100
Select * from Employee where Department='Accounts'
Select * from Employee where Department is null
Select count (*) from Employee group by Department
Explanation about the solution
1. Details are inserted using Insert statement.
2. The Department and EmpName has been updated using update statement based on Empid
3. An employee with empid is deleted using delete statements
4. The employees of Department Account have been listed
5. The employees not assigned to any department have been listed using null condition
6. The count of employees of each department is displayed using group by and aggregate function
Syntax:
SELECT column_name, aggregate_function (column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function (column_name) operator value;
Example:
SELECT Employees. LastName, COUNT (Orders.OrderID) AS NumberOfOrders
FROM Orders INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
GROUP BY LastName
HAVING COUNT (Orders.OrderID) > 10;
The above SQL statement finds if any of the employees has registered more than 10 orders:
employee and use having clause to filter for the number of order that are more than 25 and use
where clause for filtering based on the last name.
Solution
SELECT Employees.LastName, COUNT (Orders.OrderID) AS NumberOfOrders
FROM Orders INNER JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID
WHERE LastName='Davolio' OR LastName='Fuller'
GROUP BY LastName
HAVING COUNT (Orders.OrderID) > 25;
Explanation about the solution
Employee and Order table is joined using the EmployeeID foreign key in the order table (join
condition here). Then restrict the results only for the employee whose last name is 'Davolio' or 'Fuller'
using a where clause. Then restrict the count of order place using a having clause. Then we have
grouped by the last name.
1.2 Introduction
It is also called as INNER QUERY as it is placed as a part of another query called as MAIN
QUERY / OUTER QUERY.
a SELECT clause
a FROM clause
a WHERE clause
Subqueries can be used with the comparison operators such as =, <, >, >=, <=, and also
with the multiple row operators such as IN, ANY or ALL.
Execution Process:
Inner query executes first and passes the result to outer query.
Syntax:
SELECT select_list
FROM table
WHERE expression comparison_operator
(SELECT select_list
FROM table);
Inner query should return only one column when comparison operators are used in the outer
query.
The column used in the WHERE clause of outer query should be compatible with the column
information returned by the inner query.
Subqueries cannot manipulate their results internally, therefore ORDER BY clause cannot be
added in to a subquery. ORDER BY clause can be used in the main SELECT statement
(outer query).
GROUP BY and HAVING clauses cannot be used in the inner query when comparison
operators are used in the outer query.
If inner query returns a null value to the outer query, the outer query will not return any rows
when using certain comparison operators in a WHERE clause.
Subqueries that return more than one row can only be used with multiple value operators,
such as the IN operator.
The ntext, text, and image data types cannot be used in the select list of subqueries.
Note: If an error occurs while executing a subquery, execute the inner query
separately to check and fix the error.
Note: When single row operator is used, and if a subquery returns more than one row
then the query will become invalid and an error will be returned.
Multi row operator Ex: Use IN, ANY, or ALL operator in outer query to handle a subquery that
returns multiple rows.
Display the employee details of Learning and Sales Department.
SELECT emp_id, first_name, last_name, salary, designation
FROM tblemployees
WHERE dept_no IN
(SELECT dept_no
FROM tblDepartment
WHERE dept_name IN ('sales',learning))
UPDATE tblEMPLOYEES
SET salary = salary * 0.25
WHERE dept_no =
(SELECT dept_no FROM tblDepartment
WHERE dept_name = 'sales')
Outer query executes first and passes the result to inner query.
For each row of Outer query result, inner query will be executed.
Display the Departments information where at least one employee is working.
SELECT dept_no, dept_name, location
FROM tbldepartment d1
WHERE EXISTS
(SELECT * FROM tblEmployees e1 WHERE e1.dept_no=d1.dept_no)
Display the list of all employees whose salary is above the average salary for each
employees department.
SELECT emp_id, first_name, last_name
FROM tblEmployees e1
WHERE salary >
(SELECT AVG(salary)
FROM tblEmployees e2
WHERE e1.dept_no=e2.dept_no)
Now, let us join these two tables using INNER JOIN as follows:
SQL>SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID =ORDERS.CUSTOMER_ID;
This would produce the following result:
Now, let us join these two tables using LEFT JOIN as follows:
SQL>SELECT ID,NAME,AMOUNT,DATE
FROM CUSTOMERS
LEFT OUTER JOIN ORDERS
ON CUSTOMERS.ID =ORDERS.CUSTOMER_ID;
This would produce the following result:
Now, let us join these two tables using RIGHT JOIN as follows:
SQL>SELECT ID,NAME,AMOUNT,DATE
FROM CUSTOMERS
RIGHT OUTER JOIN ORDERS
ON CUSTOMERS.ID =ORDERS.CUSTOMER_ID;
This would produce the following result:
Now, let us join these two tables using FULL OUTER JOIN as follows:
SQL>SELECT ID,NAME,AMOUNT,DATE
FROM CUSTOMERS
FULL OUTER JOIN ORDERS
ON CUSTOMERS.ID =ORDERS.CUSTOMER_ID;
This would produce the following result:
Now, let us join these two tables using CROSS JOIN as follows:
SQL>SELECT ID,NAME,AMOUNT,DATE
FROM CUSTOMERS,ORDERS;
This would produce the following result:
Self Join
The SQL SELF JOIN is used to join a table to itself as if the table were two tables, temporarily
renaming at least one table in the SQL statement.
The basic syntax of SELF JOIN is as follows:
SELECT a.column_name,b.column_name...
FROM table1 a,table1 b
WHERE a.common_field =b.common_field;
Here, WHERE clause could be any given expression based on your requirement.
Consider the following two tables,
(a) CUSTOMERS table is as follows:
In the above statements we have passed values for contact number, location and id when we
execute the procedure. So the required details are updated. You can execute the same procedure
with different values which enables you to reuse the procedure.
@location varchar(30),
@id int out)
as
begin
insert into tblCustomer
values(@name,@contactNo,@location)
set @id=@@identity
end
Executing a procedure having output parameter
Declare @result int
Execute sp_insertCustomer 'Asha',9898989898,'Mumbai',@id= @result output
Print @result
Explanation:
set @id=@@identity - set keyword is used to do assignment in SQL. @@identity is a global variable
which is used to retrieve the auto generated values. It should be used next to an insert statement.
7.2. Views
View is a virtual table. It can contain columns from one or more table .View appears just like a real
table, with a set of named columns and rows of data. SQL creates the illusion like table we can even
insert, update, delete using views
Syntax to create view:
Create view <NameofView>
As
---write select query here
Syntax to execute view:
Select * from <NameOfView>
Eg. Following is the view that retrieves the employees of Admin department. View keyword is used
when creating view.
Create View adminEmployees
As
Select * from Employees where DeparmentName ='Admin'
Executing the view
Select * from adminEmployees
If a view is created from one table then it can also be used to insert, update, delete values to the
table
Insert into adminEmployees Values('Priya','5/5/2010','Admin')
Insert into adminEmployees Values('Puja','5/15/2010','IS')
The above statement will insert value to Employee table.
SqlConnection: Used to specify the connection string. Following statement is used to specify
connection string and create an object of SqlConnection
string ConnectionString = "Data Source=ServerName;" + "Initial Catalog=DataBaseName;" + "User
id=UserName;" + "Password=Secret;";
fetch the details of the required column e.g. reader ["id"]. Alternatively we can provide index we can
use reader [0], reader [1] and so on.
e.g.
// Execute procedure with select query
SqlDataReader reader= command.ExecuteReader ();
List<Customer> customerList = new List<Customer> ();
//Read row by row from reader object
while(reader.Read())
{
int id = Convert.ToInt32(reader["id"]);
string name = reader["name"].ToString();
Customer customer = new Customer(id, name);
customerList.Add(customer);
}
3) ExecuteScalar Used when select query returns a single value
E.g. int maxUser = Convert.ToInt32(command.ExecuteScalar());
8.2. Sample
Create a customer table with id, name, contact number and location. And do the following operations
1. Add customer and return the auto generated customer id
2. View all the customers
3. Retrieve contact number for a customer
Following is the sql code for the given scenario
CREATE TABLE tblCustomer(
[customerid] [int] IDENTITY(1,1) primary key,
[name] [varchar](30),
[contactNo] [bigint],
[Location] [varchar](30) )
create proc sp_viewCustomer
as
select * from tblCustomer
create proc sp_viewCustomerbyId
(@id int)
as
begin
select contactNo from tblCustomer
where customerid=@id
end
create proc sp_insertCustomer
(@name varchar(30),
@contactNo bigint,
@location varchar(30),
@id int out)
as
begin
insert into tblCustomer
values(@name,@contactNo,@location)
set @id=@@identity
end
Following is the customer Class
//Customer Class
public class Customer
{
//Attributes
int _customerId;
string _name;
int _contactNo;
string _location;
//properties
public int CustomerId { get { return _customerId; } set { _customerId = value; } }
public string Name { get { return _name; } set { _name = value; } }
public int ContactNo { get { return _contactNo; } set { _contactNo = value; } }
public string Location { get { return _location; } set { _location = value; } }
//constructor
public Customer(int id, string name, int contactNo, string location)
{
_customerId = id;
_name = name;
_contactNo = contactNo;
_location = location;
}
public Customer(string name, int contactNo, string location)
{
_name = name;
_contactNo = contactNo;
_location = location;
}
Following is the customer DB class which contains separate methods for each operation
public class CustomerDB
{
public List<Customer> getCustomers()
{
string ConnectionString = "Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
SqlConnection connection = new SqlConnection(ConnectionString);
//Connection is opened using Open method
connection.Open();
//create command object
SqlCommand command = new SqlCommand();
//Set command type as stored procedure
command.CommandType = CommandType.StoredProcedure;
//Command text is stored procedure name if command type is stored procedure
command.CommandText = "sp_viewCustomer";
//Used to relate command object to connection
command.Connection = connection;
// Execute procedure with select query
SqlDataReader reader= command.ExecuteReader();
List<Customer> customerList = new List<Customer>();
//Read row by row from reader object
while(reader.Read())
{
int id = Convert.ToInt32(reader["customerid"]);
string name = reader["name"].ToString();
Customer customer = new Customer(id,
name,Convert.ToInt32(reader["contactNo"]),reader["Location"].ToString());
customerList.Add(customer);
}
//Connection should be closed after use. Its done using close method
connection.Close();
return (customerList);
}
public int geCustomersContactNo(int id)
{
string ConnectionString = "Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
SqlConnection connection = new SqlConnection(ConnectionString);
//Connection is opened using Open method
connection.Open();
//create command object
SqlCommand command = new SqlCommand();
//Set command type as stored procedure
command.CommandType = CommandType.StoredProcedure;
//Command text is stored procedure name if command type is stored procedure
command.CommandText = "sp_viewCustomerbyId";
//Used to relate command object to connection
command.Connection = connection;
//Used to pass parameter to procedure
command.Parameters.AddWithValue("@id", id);
// Execute procedure with select query
int number = Convert.ToInt32(command.ExecuteScalar());
//Connection should be closed after use. Its done using close method
connection.Close();
return number;
}
public int addCustomers(Customer custObj)
{
string ConnectionString = "Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
SqlConnection connection = new SqlConnection(ConnectionString);
//Connection is opened using Open method
connection.Open();
//create command object
SqlCommand command = new SqlCommand();
//Set command type as stored procedure
command.CommandType = CommandType.StoredProcedure;
Console.WriteLine("Location: "+c.Location);
}
Console.ReadKey();
//code to insert a data. You can get data from user
Customer ins=new Customer("Priya",990909090,"Delhi");
int result=db.addCustomers(ins);
Console.WriteLine("Customer Added and id is " + result);
Console.ReadKey();
//code to fetch contact number of customer inserted now
int contactNo=db.geCustomersContactNo(result);
Console.WriteLine(contactNo);
Console.ReadKey();
Query 1:
Select name from Employee
Result:
Priya
Puja
Query 2:
select name from adminEmployees
Result:
Priya
Explanation:
Employee table contains both the employee of all departments but the admin
Connection:
Connection c class is used to establish a connection to database. It is required to interact with the
database
DataAdapter:
Data Adapter class is used to transfer the data between database and dataset. It needs a
connection to transfer the data.
CommandBuilder:
Command builder class is used to generate the commands which are not generated by the
DataAdapter automatically, By default, DataAdapter contains only the select command and it doesnt
contain insert, update and delete commands.
DataSet:
Dataset is used to store the data retrieved by data adapter and make it available for .net application.
It provides a consistent relational programming model regardless of the data source.
DataView:
DataView is a view of table available in DataSet. It is used to find a record, sort the records and filter
the records. By using data view, you can also perform insert, update and delete as in case of a
DataSet.
The adapter supports specific methods to move the data back and forth between the dataset and
data source.
Fill(dsname,tablename):
Opens a connection to database, executes select command, stores the data retrieved by select
command in to dataset and immediately closes the connection.
As connection to database was closed, any changes to the data in dataset will not be directly sent to
the database and will be made only in the dataset.
Update(dsname,tablename):
Transmits changes made to a dataset table to the corresponding database. When it is called, the
DataAdapter will again open the connection to database, executes insert, update and delete
commands to send changes in dataset to database and immediately closes the connection.
Dataset
Dataset is the heart of ADO.NET Disconnected architecture and is presented under System.Data
namespace. It is an in-memory representation of relational data that can store multiple data tables
from multiple data sources. The information in dataset is stored in an XML format.
The structure of a Dataset is similar to that of a relational database; it exposes a hierarchical object
model of tables, rows, columns, constraints, and relationships.
SqlConnection con
= new SqlConnection (ConfigurationManager .ConnectionStrings[connKey].ConnectionString);
2. Define the data adapter object with Select Command
Syntax:
SqlDataAdapter da = new SqlDataAdapter(select * from employees,con);
3. Define the dataset object
Syntax:
DataSet ds = new DataSet();
4. Fill the dataset object with the result of data adapters query
Syntax:
da.Fill(ds,employees);
5. Read the records from the DataTables in the datasets using the DataRow and DataColumn
objects.
Syntax:
ds.Tables[TableName / TableIndex].Rows[RowIndex][ColumnIndex]
Note: Dataview should be used whenever the data in dataset table has to be sorted, filtered or to be
projected in page wise.
Steps to perform manipulations in Disconnected Model
Following are common steps for data manipulations in disconnected model:
1. Define the connection object with appropriate connection string
Syntax:
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings[connKey].ConnectionString);
2. Define the data adapter object with Select Command
Syntax:
SqlDataAdapter da = new SqlDataAdapter(select * from employees,con);
3. Define the CommandBuilder Object.
Syntax:
SqlCommandBuilder cmb = new SqlCommandBuilder(da);
DataRow dr;
2. Search for a record in the datatable based on the given value and assign it to the DataRow object.
Syntax:
dr= ds.Tables[TableName / TableIndex].Rows.Find(PKColValue);
3. Retrieve the column values from the DataRow object and display them.
Syntax:
textBoxname.Text=dr["columnname"/ColumnIndex];
Steps to insert the record into the data table:
1. Define the datarow object.
Syntax:
DataRow dr;
2. Assign the new row of the dataset table to the row object
Syntax:
dr= datasetname.tablename.NewRow();
3. Assign the values to the columns of the datarow.
Syntax:
dr[columnname/colindex]=value;
4. Add the data row to the dataset's table.
Syntax:
ds.tablename.Rows.Add(dr);
5. Update the data adapter with the dataset table.
Syntax:
daname.Update(datasetname,tablename);
Steps to Update the record
1. Define the data row object.
Syntax: DataRow dr;
2. Assign the row which has to modified to the datarow object.
Syntax:
dr.BeginEdit();
4. Assign the new values for the columns which have to be modified.
Syntax:
dr[colname/colindex]=new value;
dr.EndEdit()
6. Call Update() on the dataadpater to update these changes in the database table.
Syntax:
da.Update(dsname,tablename);
ds.Tables[TableName / TableIndex].Rows.Find(pkcolvalue).Delete();
2. Call the Update() on the dataadapter to update the changes in the database table.
Syntax:
da.Update(dsname,tablename);
------------}
else
{
txtModelNo.Text = "";
txtIMEI.Text = "";
lblStatus.Text = "No Details found";
}
btnAddNew_Click
txtModelNo.Text = "";
txtIMEI.Text = "";
int lastRowIndex = ds.Tables[0].Rows.Count - 1;
int newClaimId = (int)ds.Tables[0].Rows[lastRowIndex][0] + 1;
txtClaimId.Text = newClaimId.ToString();
txtClaimId.ReadOnly = true;
btnSave_Click
txtClaimId.ReadOnly = false;
DataRow row = ds.Tables[0].NewRow();
row[0] = this.txtClaimId.Text;
row[1] = this.txtModelNo.Text;
row[2] = this.txtIMEI.Text;
ds.Tables[0].Rows.Add(row);
adapter.Update(ds);
lblStatus.Text = "Details are saved successfully";
btnModify_Click
DataRow row = ds.Tables[0].Rows.Find(this.txtClaimId.Text);
row.BeginEdit();
row[1] = this.txtModelNo.Text;
row[2] = this.txtIMEI.Text;
row.EndEdit();
adapter.Update(ds);
lblStatus.Text = "Details are modified successfully";
btnRemove_Click
ds.Tables[0].Rows.Find(this.txtClaimId.Text).Delete();
adapter.Update(ds);
lblStatus.Text = "Details are removed successfully";
this.txtClaimId.Text = "";
this.txtModelNo.Text = "";
this.txtIMEI.Text = "";
}
Explanation about the solution
Step 1: Include all the required namespaces
Step 2: Store the connection string in web.config file because all these actions need to connect to
the same database.
Step 3: DataAdapter and DataSet are declared as Class level members as these are required for
each CRUD operation.
Step 4: As DataAdapter is defined with only Select Command, we cant perform manipulations. So,
CommandBuilder object is used to generate other commands to do manipulations. Primary key is
defined before generating the CommandBuilder object, to generate all Commands.