Professional Documents
Culture Documents
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
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.
• To tell SQL Server that we’re logging in using Windows Authentication, we’d use a
connection string that included Integrated Security=True,
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
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";
conn.Open();
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();
String sql;
sql = "SELECT * FROM phones";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
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 />";
}
sql = "SELECT * FROM phones where name ='" + TextBox1.Text + "' ";
Example searching phone number based on his name
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
comm.Parameters.Add("@EmployeeID", System.Data.SqlDbType.Int);
comm.Parameters["@EmployeeID"].Value = idTextBox.Text
Or
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.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
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
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
– “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" />
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
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
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
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();
}
• 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);
string sql;
sql = "insert into book(title,info,bookquantity,price, imgfile) values ( '" +
TextBox1.Text + "' , '" + TextBox2.Text + "' , '" + TextBox3.Text + "' , '" + TextBox4.Text + "' ,'" +
imgfile + "' )";
1- to set hyperlink that shows title and send id to Detailpage.aspx using query string method
<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>
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();
mail.To.Add ((string)reader["email"]);
}
reader.Close();
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
//new way
var conString = System.Configuration.ConfigurationManager.ConnectionStrings[“dadConnectionString"];
conn = new SqlConnection(conString.ConnectionString);
Working with the dataGrid events
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
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();
}
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;
}