You are on page 1of 82

ADO.

NET
Introduction
• In order to use ADO.NET, we must first decide which kind of database
we’ll use .
• Since we’re using SQL Server, you’ll need to import the
• System.Data.SqlClient namespace. This contains all the required Sql
classes, the most important of which are:
• SqlConnection : This class exposes properties and methods for
connecting to an SQL Serverdatabase.
• SqlCommand This class holds data about the SQL queries and stored
procedures that you in-tend to run on your SQL Server database.
• SqlDataReaderData is returned from the database in an SqlDataReader
class..
Steps of Getting data from DB using DataReader and GridView

• 1- new connection (connection string)


• 2- sql statement ( select ---
• 3- command sql command
• 4- open connection
• 4- data reader execute reader
• 5- data grid view fill from reader
• 6- close reader and connection

<asp:GridView id="grid" runat="server" />

Chapter 10 – Slide 3
Defining the Database Connection
• create a new instance of the SqlConnection, which will facilitate our connection
to the database.

• A typical connection string for an SQL Server Express database looks like this:

• The connection string must specify the name of the server on which the
database is located.
• we also specify the database we want to connect to, and provide any
required authentication details (the user ID, and the password for that user
account).
Defining the Database Connection (Cont.)
• SQL Server supports two methods of authentication: SQL Server Authentication and
Windows Authentication.

• The form of authentication to connect to SQL Server Windows Authentication,


which doesn’t require you to supply a SQL Server name and password, but instead
uses the credentials of your Windows user account.

• To tell SQL Server that we’re logging in using Windows Authentication, we’d use a
connection string that included Integrated Security=True,

The form of authentication to connect to SQL Server is SQL Server Authentication


, which require you to supply a SQL Server name and password
Defining the Database Connection Example
• 1- new connection (connection string)

// using SQL express local server and database university

SqlConnection conn = new SqlConnection("Data


Source=localhost\\SqlExpress;
Initial Catalog=university;Integrated Security=True");

//Using local dd.mdf database

SqlConnection conn1 = new SqlConnection("Data Source=(LocalDB)\\


MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\dd.mdf;Integrated
Security=True");
Creating Database Using SQL express In Visual.NET

Chapter 10 – Slide 7
Chapter 10 – Slide 8
Creating Tables usig mdf
Enter the new DB name
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\yaman\Documents\test.mdf;Integrated
Security=True;Connect Timeout=30

Add \ to \\ at the connection string


Data Source= (LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\yaman\\Documents\\
test.mdf;Integrated Security=True;Connect Timeout=30
Creating a table

4
2

5
To fill table with data
2. Preparing the Command

• Now we’re at step three, in which we create an SqlCommand object and pass
in our SQL statement.

• The SqlCommand object accepts two parameters. The first is the SQL
statement, and the second is the connection object that we created in the
previous step:
4. Executing the Command
• When we’re ready to run the query, we open the connection and execute the

command.

• The SqlCommand class has three methods that we can use to execute a command; we

simply choose the one that meets the specific needs of our query. The three methods

are as follows:

• ExecuteReader
• is used for queries or stored procedures that return one or more
rows of data.
• ExecuteReader returns an SqlDataReader object that can be used
to read the results of the query one by one, in a forward-only,
read-only manner.
• SqlDataReader object can’t be used to update the data or to
access the results in random order.
• for each connection you can open only one SqlDataReader object
4. Executing the Command (Cont.)
• The SqlDataReader keeps the database connection open until all the records
have been read.

• This can be a problem, as the database server will usually have a limited number
of connections—people who are using your application simultaneously may
start to see errors if you leave these connections open.

• ExecuteScalar
• is used to execute SQL queries or stored procedures that return a single value,
such as a query that counts the number of employees in a company.

• ExecuteNonQuery
• Is used to execute stored procedures and SQL queries that insert, delete, or
update data. The return value will be the number of affected rows.
E.g. Getting data from DB using DataReader and GridView
using System.Data.SqlClient;
….
// using SQL express database Example
SqlConnection conn = new SqlConnection("Data Source= localhost\\SqlExpress;Initial
Catalog=;Integrated Security=True");

String sql;
sql = "SELECT * FROM phones";

SqlCommand comm = new SqlCommand(sql, conn);

conn.Open();

SqlDataReader reader = comm.ExecuteReader();

GridView1.DataSource = reader;
GridView1.DataBind();

reader.Close();
conn.Close();
Binding data view Controls

The .NET Framework comes bundled with a few controls that can help us to display
more complex lists of data: Repeater, DataList, GridView, DetailsView. These controls
allow you to format database data easily within anASP.NET page.

Binding GridView
reader = comm.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();

Binding Reperter
reader = comm.ExecuteReader();
employeesRepeater.DataSource = reader;
employeesRepeater.DataBind();

Binding List item


reader = comm.ExecuteReader();
categoryList.DataSource = reader;
categoryList.DataTextField = "Category";
Repeater Control example
<asp:Repeater ID="myRepeater" runat="server">
<HeaderTemplate>
<table width="400" border="1">
<tr>
<th>Employee ID</th>
<th>Name</th>
<th>Username</th>
<th>Password</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("EmployeeID") %></td>
<td><%# Eval("Name") %></td>
<td><%# Eval("Username") %></td>
<td><%# Eval("Password") %></td>
</tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate> </asp:Repeater>
Drop list contain user names example

SqlConnection conn = new SqlConnection("Data Source=localhost\\


SqlExpress;Initial Catalog=dad;Integrated Security=True");

String sql;
sql = "SELECT * FROM phones";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();

SqlDataReader reader = comm.ExecuteReader();

employeesList.DataSource = reader;
employeesList.DataValueField = "stname";
employeesList.DataBind();
reader.Close();
conn.Close();
Reading Multi-record data row by row
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
employeesLabel.Text += (string)reader["Name"] + "<br />";
}

Search Example search employee by their name


sql = "SELECT * FROM phones where name ='Ali' ";

Using textbox to get the name  " + TextBox1.Text + "

sql = "SELECT * FROM phones where name ='" + TextBox1.Text + "' ";
Example searching phone number based on his name

SqlConnection conn = new SqlConnection("Data Source= localhost\\SqlExpress;Initial


Catalog=dad;Integrated Security=True");

string sql;
sql = "SELECT * FROM phones where name ='" + TextBox1.Text + "' ";
SqlCommand comm = new SqlCommand(sql, conn);

conn.Open();
SqlDataReader reader = comm.ExecuteReader();

if (reader.Read())
{ Label1.Text = Convert.ToString((int)reader["number"]) ; }
else
{ Label1.Text = "no user found "; }
reader.Close();
conn.Close();
More advance search queries
Query 1 - Retrieve the name and address of all employees who work
for an --department

Research

select fname,lname,address
from employee,department
where Dnumber=Dno and Dname ='" + TextBox1.Text + "'
Using Parameters with Queries
• However, if—as is perhaps more likely—the user entered an
employee’s name E’mad
• This query would cause an error in the database, which would, in turn,
cause anexception in your web form

Special Characters such as ‘ && ; are not permitted at sql


statements and might enable hackers to hack your database
Adding parameters

comm.Parameters.Add("@EmployeeID", System.Data.SqlDbType.Int);
comm.Parameters["@EmployeeID"].Value = idTextBox.Text

Or

comm.Parameters.AddWithValue("@EmployeeID ", idTextBox.Text);

Using parameter in sql

"SELECT EmployeeID, Name, Username, Password FROM Employees WHERE


EmployeeID=@EmployeeID"
SqlConnection conn;
SqlCommand comm; SqlDataReader reader; conn = new
SqlConnection("Server=localhost\\SqlExpress;" + "Database=Dorknozzle;Integrated
Security=True");
comm = new SqlCommand( "SELECT EmployeeID, Name, Username, Password " +
"FROM Employees WHERE EmployeeID=@EmployeeID", conn);
int employeeID;

comm.Parameters.AddWithValue("@EmployeeID ", TextBox1.Text);

conn.Open();
reader = comm.ExecuteReader();
if (reader.Read()) {
userLabel.Text = "Name: " + reader["Name"] + "<br />" +
"Password: " + reader["Password"]; }
else
{
userLabel.Text = "There is no user with this ID: " + employeeID;
}
reader.Close();
conn.Close();
Another example
cnn.Open();

cmd = new SqlCommand("insert into tbl_holiday values(@EmNum,


@holyday)",cnn);

cmd.Parameters.AddWithValue("@EmNum", txtNum.Text);
cmd.Parameters.AddWithValue("@holiday", txtHoliday.Text);
cmd.ExecuteNonQuery();
ExecuteScalar Example
• 1- new connection
• 2- sql statement (SELECT COUNT( Id) ---)
• 3- command sql command
• 4- execute ExecuteScalar command
• 4- close

Example : number of failed student in a class


sql = "SELECT COUNT( Id) FROM student where status =‘failed' and
classid = '" + TextBox1.Text + "'";
comm = new SqlCommand(sql, conn);
int count = (int)comm.ExecuteScalar();
Label2.Text = Convert.ToString(count);
Chapter 10 – Slide 27
Inserting data
• 1- new connection
• 2- sql statement (insert ---)
• 3- command sql command
• 4- execute non Query command
• 4- close

Chapter 10 – Slide 28
Example Inserting phone record from textboxes
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");
String sql;
sql = "insert into phones(name,number,place,male,female,birth) values ( '" +
TextBox1.Text + "' , '" + TextBox2.Text + "' , '" + DropDownList1.Text + "' , '" +
RadioButton1.Checked + "' , '" + RadioButton2.Checked + "' , '" + TextBox3.Text + "' )";
SqlCommand comm = new SqlCommand(sql, conn);

conn.Open();
comm.ExecuteNonQuery();

conn.Close();

TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
DropDownList1.ClearSelection();
Label1.Text = "sucessfully inserted";
Dealing with Arabic Characters

string sql = "insert into admins(name,pass) " +


"values (N'" + TextBox1.Text + "',N'" + TextBox2.Text + "')";

sql = "SELECT * FROM customer where name =N'" + TextBox1.Text + "'";


Working with ID

ID should be auto
incremented in the database
and no need to include it in a
textbox or in the insert
statement ;
Working with Date

To set the default date to


today when inserting new
record table use (getdate())

to get the date from the system


DateTime d1,d2;
d1 = DateTime.Now; // GETTING DATE TIME
d2 = DateTime.Today; //GETTING DATE

To print the date and time


Label1,Text = d1.ToString("yyyy-MM-dd HH:mm:ss");

To Print only date


Label2,Text = d2.ToString("yyyy-MM-dd");
Working with Date

to get last month


string PastMonthDate = DateTime.Today.AddDays(-30).ToString();

to get the month or year


string currentMonth = DateTime.Today.Month.ToString();
string currentYear = DateTime.Today.Year.ToString()

Select FROM registrations WHERE year = '" + currentYear + "' ";

Example To display the today date(default) at a textbox

– “TextMode = date “
TextBox23.Text = DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd");
Reading Back the Date from a database

if (reader.Read())
{
DateTime d1 = (DateTime)reader["redate"];
TextBox23.Text = d1.ToString("yyyy-MM-dd"); } // TextMode date
reader.Close();

// note to convert to USA English this you need to change time format in config file
<system.web>
<globalization culture="en-US" uiCulture="en-US" />

// to convert from English to hijree


<globalization culture="ar-SA" uiCulture=" ar-SA " />
Example: Filling the form based on name

protected void TextBox1_TextChanged(object sender, EventArgs e)


{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");

string sql;
sql = "SELECT * FROM phones where name ='" + TextBox1.Text + "' ";
SqlCommand comm = new SqlCommand(sql, conn);

conn.Open();
SqlDataReader reader = comm.ExecuteReader();

if (reader.Read())
{
TextBox2.Text = ((string)reader["number"]);
DropDownList1.Text = ((string)reader["place"]);
RadioButton1.Checked = ((Boolean)reader["male"]);
RadioButton2.Checked = ((Boolean)reader["female"]);
DateTime d1 = (DateTime)reader["birth"];
TextBox3.Text = d1.ToString("yyyy-MM-dd");
}
reader.Close();
conn.Close();
}
Updating data
• 1- new connection
• 2- sql statement (update ---)
• 3- command sql command
• 4- execute non Query command
• 4- close

Chapter 10 – Slide 36
Example Updating phone number based on his name

SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial


Catalog=mynewdb;Integrated Security=True;Pooling=False");
String sql;

sql = "update phones set number ='" + TextBox2.Text + "' , male = '" +
RadioButton1.Checked + "' , female = '" + RadioButton2.Checked + "' , place = '" +
DropDownList1.Text + "' , birth = '" + TextBox3.Text + "' where name ='" + TextBox1.Text
+ "'";
SqlCommand comm = new SqlCommand(sql, conn);
try
{
conn.Open();
comm.ExecuteNonQuery();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
DropDownList1.ClearSelection();
Label1.Text = "sucessfully updated";
}
catch (Exception ex)
{ Label1.Text = "Exception!<br />" + ex.Message; }

finally { conn.Close(); }
Deleting data
• 1- new connection
• 2- sql statement (delete ---)
• 3- command sql command
• 4- execute non Query command
• 4- close

Chapter 10 – Slide 38
Example deleting phone record based on his name
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");
String sql;

sql = "delete from phones where name ='" + TextBox1.Text + "' ";
SqlCommand comm = new SqlCommand(sql, conn);
try
{
conn.Open();
comm.ExecuteNonQuery();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
DropDownList1.ClearSelection();
Label1.Text = "sucessfully deleted ";
}
catch (Exception ex)
{ Label1.Text = "Exception!<br />" + ex.Message; }

finally { conn.Close(); }
Advance Example 1: Login example
role password name
admin 1111 aiman
customer 1234 ali (users table)
customer 6666 emad

Use varchar type for columns


Login Page Button 1 click event
string pass = "pppp" ,rol = "rrrr" , sql ;
SqlConnection conn = new SqlConnection("Data Source=localhost\\SqlExpress;Initial Catalog=dad;Integrated
Security=True");
sql = "SELECT * FROM users where name ='" + TextBox1.Text + "' and pass ='" + TextBox2.Text + "' ";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
if (reader.Read())
{ Session[“role"] = (string)reader["role"] ;
Session[“username"] = (string)reader[“name"] ;
Session[“userId"] = (string)reader[“Id"] ;

if (Session[“role"] == "admin")
Server.Transfer(“admin_home.aspx");
else
Server.Transfer(“customer_home.aspx");
}
else
{ Label1.Text = "no user found or password "; }
reader.Close(); conn.Close();
All secured Pages
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

if ((string)Session["role"] != "admin" )
Server.Transfer(“login.aspx");
......
.....
....
}
Advance Example 2: Cascading dropdown lists

Enable indexChanged event for DropList1

At droplist1 selectedIndexChange event {

sql = "SELECT name FROM phones where place = '"+ DropDownList1.SelectedItem.Text+ "'";

DropList1
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");
conn.Open();
string sql = "SELECT distinct(place) FROM phones";
SqlCommand comm = new SqlCommand(sql, conn);
SqlDataReader reader = comm.ExecuteReader();
DropDownList1.DataSource = reader;
DropDownList1.DataTextField = "place";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select here...", string.Empty));
reader.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");
conn.Open();
string sql = "SELECT name FROM phones where place = '"+
DropDownList1.SelectedItem.Text+ "'";
SqlCommand comm = new SqlCommand(sql, conn);
SqlDataReader reader = comm.ExecuteReader();
DropDownList2.DataSource = reader;
DropDownList2.DataTextField = "name";
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem("Select here...", string.Empty));
reader.Close();
}
Advance Example 3: Searching Example

To enable TextChanged,
SelectIndexChanged event for :
TextBox1, ListBox1
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");
conn.Open();
string sql = "SELECT * FROM phones where name like '%" + TextBox1.Text + "%'";
SqlCommand comm = new SqlCommand(sql, conn);
SqlDataReader reader = comm.ExecuteReader();
ListBox1.DataSource = reader;

ListBox1.DataTextField = "name";
ListBox1.DataValueField = "Id";
ListBox1.DataBind();
reader.Close();
}

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)


{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");
conn.Open();
string sql = "SELECT * FROM phones where id = '" + ListBox1.SelectedItem.Value + "'";
SqlCommand comm = new SqlCommand(sql, conn);
SqlDataReader reader = comm.ExecuteReader();
if (reader.Read())
{
Label1.Text = (string)reader["number"];
Label2.Text = (string)reader["place"];
DateTime d1 = (DateTime)reader["birth"];
Label3.Text = d1.ToString("yyyy-MM-dd");
}
reader.Close();
}
Advance Example 4: Creating Catalog using Repeater
Component

• When the name is clicked a second page with more item detail will be shown
Example: How to upload and insert image

if (FileUpload1.FileName != "")
{
string imgfile = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("images") + "\\" + imgfile);

SqlConnection conn = new SqlConnection("Data Source=localhost\\SqlExpress;Initial


Catalog=mynewdb;Integrated Security=True");

string sql;
sql = "insert into book(title,info,bookquantity,price, imgfile) values ( '" +
TextBox1.Text + "' , '" + TextBox2.Text + "' , '" + TextBox3.Text + "' , '" + TextBox4.Text + "' ,'" +
imgfile + "' )";

SqlCommand comm = new SqlCommand(sql, conn);


conn.Open();
comm.ExecuteNonQuery();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
Label1.Text = "sucessfull inserted ";
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=mynewdb;Integrated
Security=True;Pooling=False");
string sql;
sql = "SELECT * FROM book where title ='" + TextBox1.Text + "' ";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
search/edit image
if (reader.Read())
{
TextBox2.Text = ((string)reader["info"]);
TextBox3.Text = Convert.ToString((int)reader["bookquantity"]);
TextBox4.Text = Convert.ToString((int)reader["price"]);
Image1.ImageUrl = "~//images//" + ((string)reader["imgfile"]);
Label2.Text = ((string)reader["imgfile"]);
}
reader.Close();
conn.Close();
}

protected void Button2_Click(object sender, EventArgs e)


{
string imgfile = "";
if (FileUpload1.FileName != "")
{
imgfile = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("images") + "\\" + imgfile);
}
else imgfile = Label2.Text;
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=mynewdb;Integrated
Security=True;Pooling=False");
String sql;
sql = "update book set info ='" + TextBox2.Text + "' , bookquantity = '" + TextBox3.Text + "' , price =
'" + TextBox4.Text + "' , imgfile = '" + imgfile + "' where title ='" + TextBox1.Text + "'";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
TextBox1.Text = "";TextBox2.Text = "";TextBox3.Text = "";TextBox4.Text = "";
Label1.Text = "sucessfull inserted ";
}
to show image according to its imagefile name

<asp:Image ID="Image1" runat="server"


ImageUrl='<%#"~//images//"+Eval("imgfile")%>' />

For Passing data to a different page:


• Query string (usually with hyperlinks)
• Session variable (usually for passing to multiple pages )

1- to set hyperlink that shows title and send id to Detailpage.aspx using query string method

name: <asp:HyperLink ID="HyperLink1" runat ="server"


NavigateUrl='<%# “Detailpage.aspx?idd="+ Eval("Id") %> '>
<%# Eval(“title") %> </asp:HyperLink>

2- to read query string idd value at Detailpage.aspx


Request.QueryString["idd"]
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table border="1">
</HeaderTemplate>

<ItemTemplate>
<tr><td>
Title: <asp:HyperLink ID="HyperLink1" runat ="server" NavigateUrl='<%#
"Detailpage.aspx?idd="+ Eval("Id") %> '> <%# Eval("title") %>
</asp:HyperLink>
<br /> <asp:Image ID="Image1" Height="61px" runat="server" ImageUrl
='<%#"~//images//"+Eval("imgfile")%>' />
<br />
<asp:Label ID="Label1" runat="server" Text='<%# Eval("price") %>'>
</asp:Label>
</td></tr>
</ItemTemplate>

<FooterTemplate></table></FooterTemplate>

>asp:Repeater/<
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=
localhost\\SqlExpress;Initial Catalog=mynewdb;Integrated
Security=True");
String sql;
sql = "SELECT * FROM book";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
Repeater1.DataSource = reader;
Repeater1.DataBind();
reader.Close();
conn.Close();
}
Detailpage code
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=
localhost\\SqlExpress;Initial Catalog=mynewdb;Integrated Security=True");
string sql;
sql = "SELECT * FROM book where Id ='" + Request.QueryString["idd"] + "' ";
SqlCommand comm = new SqlCommand(sql, conn);

conn.Open();
SqlDataReader reader = comm.ExecuteReader();

if (reader.Read())
{
Label1.Text = Convert.ToString((int)reader["Id"]);
Label2.Text = (string)reader["title"];
Label3.Text = (string)reader["info"];
Label4.Text = Convert.ToString((int)reader["price"]);
Image1.ImageUrl = "~//images//" + (string)reader["imgfile"]; ;

reader.Close();
conn.Close();

}
Using Bootstrap cards to show the catalogue
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></ script>

<asp:Repeater ID="Repeater1" runat="server" >


<HeaderTemplate>
<div class="container-fluid">
<div class="row">
</HeaderTemplate>
<ItemTemplate>
<div class="col-md-3">
<div class="card">
<div class="card-header">
ID: <asp:Label ID="Label2" runat="server"
Text='<%#Eval("Id")%>'></asp:Label>
</div>
<div class="card-body">
<asp:Image ID="Image1" Height="150px" Width="150px" runat="server"
ImageUrl ='<%#"~//images//"+Eval("imgfile")%>' /> <br />
Title:
<asp:Label ID="Label3" runat="server"
Text='<%#Eval("title")%>'></asp:Label>
</div>
<div class="card-footer">
<asp:HyperLink ID="HyperLink1" runat ="server"
NavigateUrl='<%# "Detailpage.aspx?idd="+ Eval("Id") %> '> more </asp:HyperLink>
</div>
</div> </div>
</ItemTemplate>
<FooterTemplate></div> </div></FooterTemplate>
</asp:Repeater>
Advance Example 5: a Buying Example

1- update the quantity when a buy is done, for example


sql =“ UPDATE book SET bookquantity = bookquantity - '" + TextBox2.Text + "'
where (id ='" + Request.QueryString["idd"] + "' )";
2- insert the buy record in the order table

sql = "SELECT * FROM book where id ='" +


Request.QueryString["idd"] + "' ";
comm = new SqlCommand(sql, conn);
SqlDataReader reader = comm.ExecuteReader();
if (reader.Read())
TextChange Event {
Label1.Text = (string)reader["title"];
Label2.Text = " Total: " +
((int)reader["price"] *Convert.ToInt16( TextBox1.Text));
}
reader.Close();
Advance Example 5: Buying code

SqlConnection conn = new SqlConnection("Data Source= localhost\\SqlExpress;Initial


Catalog=mynewdb;Integrated Security=True");

string sql;
sql = "UPDATE book SET bookquantity = bookquantity - '" + TextBox1.Text
+ "' where (id ='" + Request.QueryString["idd"] + "' )";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();

Session["userid"] = "1";// should be assigned at login


sql = "insert into orders (userid,bookid,quantity) values ( '" +
(string)Session["userid"] + "' , '" + Request.QueryString["idd"] + "', '" +
TextBox1.Text + "' )";
comm = new SqlCommand(sql, conn);
comm.ExecuteNonQuery();
conn.Close();
Label3.Text = "thank you for buying from our store";
Advance Example 6: Sending email to list of
student at a class
protected void Button1_Click(object sender, EventArgs e)
{
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
var mail = new MailMessage();
mail.From = new MailAddress(useremail);

// to add multiple email address

string sql = "SELECT * FROM student ";


SqlCommand comm = new SqlCommand(sql, conn);
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{

mail.To.Add ((string)reader["email"]);
}
reader.Close();

if (TextBox2.Text != "") mail.CC.Add(TextBox2.Text); // add cc


//upload attchements
if (FileUpload1.HasFile) {
mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream,
FileUpload1.FileName)); }

mail.Subject = TextBox3.Text;
mail.IsBodyHtml = true;
string htmlBody;
htmlBody = TextBox4.Text + "<br/>" + Label4.Text;
mail.Body = htmlBody;
SmtpServer.Port = 587;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new
System.Net.NetworkCredential(useremail, userpass);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
Label3.Text = "Email sent.";
Building Complex Query’s using Query Builder
https://www.youtube.com/watch?v=uexEeFMjx8U
Managing Content Using GridView
• We can create several types of columns in a GridView i. For
instance, we could create a ButtonField column, which displays a
button in each row.
• That button could be, SELECT, UPDATE,DELET, INSERT
• We could use these button in many project to manage the contents
directly in the table
Using Wizard to manage data in GridView
This approach is
good for editing
and deleting a
record
Getting the connection string from the Config file
Connection name (public in all pages) Connection string

To get this connection from any page of your project


//old way
//conn = new SqlConnection("Data Source= localhost\\SqlExpress;Initial Catalog=dad;Integrated Security=True");

//new way
var conString = System.Configuration.ConfigurationManager.ConnectionStrings[“dadConnectionString"];
conn = new SqlConnection(conString.ConnectionString);
Working with the dataGrid events

1. Create GridView with buttons (register, buy, view, etc)


2. Create GridView commands (register, buy, view, etc)
3. Placing the implementation code
protected void GridView1_RowCommand

For implementing need to get the row selected


int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];

For getting the cell that contain for e.g. the item name you need to
count cells starting from zero
nameee = row.Cells[3].Text;
1. Creating GridView with buttons (select, Update, Delete)

•2
Using RowCommand event

Note cannot use Edit, Delete, Select


These are reserved Command Names

Cell 2
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=
localhost\\SqlExpress;Initial Catalog=mynewdb;Integrated Security=True");
String sql;
sql = "SELECT Id,title FROM book";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
conn.Close();

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)


{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Session["bookid"] = row.Cells[2].Text;
if (e.CommandName == "show")Server.Transfer("Detailpage.aspx");
if (e.CommandName == "buy")Server.Transfer("Buypage.aspx");

}
Detailpage code
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=
localhost\\SqlExpress;Initial Catalog=mynewdb;Integrated Security=True");
string sql;
sql = "SELECT * FROM book where Id ='" + (string)Session["bookid"]+ "'
";
SqlCommand comm = new SqlCommand(sql, conn);

conn.Open();
SqlDataReader reader = comm.ExecuteReader();

if (reader.Read())
{
Label1.Text = Convert.ToString((int)reader["Id"]);
Label2.Text = (string)reader["title"];
Label3.Text = (string)reader["info"];
Label4.Text = Convert.ToString((int)reader["price"]);
Image1.ImageUrl = "~//images//" + (string)reader["imgfile"]; ;

reader.Close();
conn.Close();

}
Objects and Classes
- Once we’ve defined a class, we can write code that creates
objects of that class
- using the class a little like a template.
- This means that objects of a particular class expose (or make
available) the methods and properties defined by that class.
Declartion
public int strId ;
public string strFirstName ;
pivate Student graduate;

instances:
Student freshman = new Student();

Assign values to the object's members with the dot (.) operator.
freshman.strFirstName = "Joy"
freshman.strLastName = "Robinson"
freshman.strId = "23G79
Mehods
freshman.Sit();

List of instances
list <Student> freshmanList = new <Student>();
freshmanList .Add(freshman);
from the Add New Item add the Items class

phones.cs
Define all attributes of the class
public class items
{
public int Id { get; set; }
public string name { get; set; }
public string number { get; set; }
public string place { get; set; }
public Boolean male { get; set; }
public Boolean female { get; set; }
public DateTime birth { get; set; }
}
Shortcut to create properities
class items
Define all the items class constructors
public phones()
{}
public phones(string name, string number, string place, bool male, bool female, DateTime birth)
{
this.name = name;
this.number = number;
this.place = place;
this.male = male;
this.female = female;
this.birth = birth;
}

Shortcut to create a Constructor


Example: searchusers method
public void searchusers (string username)
{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");
string sql;
sql = "SELECT * FROM phones where name ='" + username + "' ";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
if (reader.Read())
{
this.number = ((string)reader["number"]);
this.place = ((string)reader["place"]);
this.male = ((Boolean)reader["male"]);
this.female= ((Boolean)reader["female"]);
this.birth = (DateTime)reader["birth"];
}
reader.Close();
conn.Close();
Example: insert method

public void insert()


{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");
String sql;
sql = "insert into phones(name,number,place,male,female,birth) values ( '" +
name + "' , '" + number + "' , '" + place + "' , '" + male + "' , '" + female + "' , '" +
birth.ToString("yyyy-MM-dd") + "' )";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
Example: delete method

public void delete(string username)


{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");
String sql;
sql = "delete from phones where name ='" + username + "' ";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
implementing update method
public void update()
{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");
string sql = "update phones set number ='" + number + "' , male = '" + male + "' , female = '" +
female + "' , place = '" + place + "' , birth = '" + birth .ToString("yyyy-MM-dd") + "' where
name ='" + name + "'";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
phones ph = new
phones(TextBox1.Text,TextBox2.Text,DropDownList1.Text,RadioButton1.Checked,R
adioButton2.Checked,Convert.ToDateTime( TextBox3.Text));
ph.insert();
TextBox1.Text = "";TextBox2.Text = "";TextBox3.Text =
"";DropDownList1.ClearSelection();
Label1.Text = "sucessfully inserted";
}

protected void TextBox1_TextChanged(object sender, EventArgs e)


{
phones ph1 = new phones();
ph1.searchusers(TextBox1.Text);
TextBox2.Text = ph1.number;
DropDownList1.Text = ph1.place;
RadioButton1.Checked = ph1.male;
RadioButton2.Checked = ph1.female;
DateTime d1 = ph1.birth;
TextBox3.Text = d1.ToString("yyyy-MM-dd");
}
protected void Button2_Click(object sender, EventArgs e)
{
phones ph = new
phones(TextBox1.Text,TextBox2.Text,DropDownList1.Text,RadioButton1.Checked,R
adioButton2.Checked,Convert.ToDateTime( TextBox3.Text));
ph.update();
TextBox1.Text = "";TextBox2.Text = "";TextBox3.Text = "";
DropDownList1.ClearSelection();
Label1.Text = "sucessfully updated"; }
protected void Button3_Click(object sender, EventArgs e)
{
phones ph1 = new phones();
ph1.delete(TextBox1.Text);
TextBox1.Text = "";TextBox2.Text = "";TextBox3.Text =
"";DropDownList1.ClearSelection();
Label1.Text = "sucessfully deleted ";
}

You might also like