1 / 29

ASP.NET Rina Zviel-Girshin Lecture 4

ASP.NET Rina Zviel-Girshin Lecture 4. Overview. Data Binding Data Providers Data Connection Data Manipulations. Web browser. DB Management System. Network OS. Input Output. Processing. Storage. Database server. Client’s PC. Web-server. Web-Application Development.

lperalta
Download Presentation

ASP.NET Rina Zviel-Girshin Lecture 4

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ASP.NET Rina Zviel-Girshin Lecture 4

  2. Overview • Data Binding • Data Providers • Data Connection • Data Manipulations

  3. Web browser DB Management System Network OS Input Output Processing Storage Database server Client’s PC Web-server Web-Application Development Hardware components Web software components Information processing Developer tools HTML XML JavaScript CSS VBScript ASP C# ASP.NET SQL DBMS

  4. ASP.NET and Data • Data access and reporting are very important to web-based systems. • Usually data items received from DataBases. • ASP.NET framework includes a rich set of classes • (DataSet, DataReader) and • controls (DataGrid, Repeater, DataList, ListBox) to work with database data. • Web-page designer has to connect/to bind data to the control. • Data can be a single value, a list of values or a collection of values.

  5. Data Binding • Data binding is a process of retrieving data from a source and dynamically associating it to a property of some visual element. • In web-based systems a visual element can be an HTML tag or .NET control. • Exists 2 types of data binding: • simple • connection between one piece of data and a server control • and complex • binds a list control (ListBox) or iterative control (Repeater) to one or more columns of data.

  6. Data Source • Usually data binding is performed to fill some list with selectable items from an imported data source • like an ArrayList, a HashTable, a database (DataReader, DataView), an XML file or a script. • Data is bind to the control via DataSource property. • The value of DataSource defines the data source and initialized to collection of data items. • <asp:RadioButtonList id="rb" runat="server" /> • and later in some script: • rb.DataSource=someArrayList • This is a logical link. Nothing happens. • Later a DataBind() method is called to load data from associated data source.

  7. Simple Data Binding Example The Page_Load method runs EVERY time the page is loaded. <%@ Page Language="C#"%> <script  runat="server">void Page_Load() {if(!Page.IsPostBack) {ArrayList countries=new ArrayList();   countries.Add("Norway");   countries.Add("Sweden");   countries.Add("France")   countries.Add("Israel")ddl.DataSource=countries;DataBind();} } A postback of a page means posting back to the same page.  You can differentiate between the page’s first request and any postbacks by using the Page.IsPostback property.

  8. Simple Data Binding Example void displayMessage(Object s,EventArgs s){ lbl.text="Your favorite country is: " + ddl.SelectedItem.Text;} </script><html><body><form runat="server"><asp:DropDownList id="ddl" runat="server"AutoPostBack="True" onSelectedIndexChanged="displayMessage" /> <p><asp:label id="lbl" runat="server" /></p></form></body></html>

  9. Output onSelectedIndexChanged ="displayMessage"

  10. DataBind() method • DataBind() is a method of the Page class and all server controls. • When DataBind method on a parent control is called it cascades to all of the children of the control. • Calling DataBind on the Page causes all data binding expressions on the page to be evaluated. • DataBind() method causes all data binding expressions on the page to be evaluated • evaluates all <%# %> expressions within the page • evaluates all data bound properties of the controls.

  11. DataBind() method • Syntax of calling DataBind on the Page: • Page.DataBind() or • DataBind() • DataBind is commonly called from the Page_Load event. protected void Page_Load(Object Src, EventArgs E) { DataBind(); // or Page.DataBind(); } • However it can be called from another procedure (next example).

  12. Example <html><head> <script language="C#" runat="server"> void SubmitBtn_Click(Object sender, EventArgs e) { Page.DataBind(); } </script> </head><body> <h3><font face="Verdana">Data binding to a property of another server control</font></h3> <form runat="server" ID="Form1"> <asp:DropDownList id=“CityList" runat="server"> <asp:ListItem>Jerusalem</asp:ListItem> <asp:ListItem>Haifa</asp:ListItem> <asp:ListItem>Tel-Aviv</asp:ListItem> <asp:ListItem>Lod</asp:ListItem> <asp:ListItem>Netanya</asp:ListItem> <asp:ListItem>Hadera</asp:ListItem> <asp:ListItem>Ashdod</asp:ListItem> </asp:DropDownList> <asp:button Text="Submit" OnClick=" SubmitBtn_Click" runat="server" ID="Button1"/> <p> Selected City: <asp:label text='<%# CityList.SelectedItem.Text %>' runat="server" ID="Label1"/></p> </form></body></html>

  13. Output Rather than explictly get the variable from the “CityList" ' and then manipulate a label control a Page.DataBind call is performed. This evaluates any <%# %> expressions within the page, including -<%#CityList.SelectedItem.Text %>

  14. DataBinding with a DataView • A DataView is a great class for presenting data to the user in a more user-friendly format. • A DataView represents a databindable, customized view of a DataTable. • The DataView and DataTable classes are defined in the System.Data namespace. • ADataTablerepresents one table of in-memory data. • Data columns should be defined and added to DataTable dt (dt.Columns.Add ) and later data rows should be added (dt.Rows.Add). • To view a DataTable you need to use a DataView or a DataSet class.

  15. Example <%@ Import namespace="System.Data" %> <html><head><script language="C#" runat="server"> void Page_Load(Object sender, EventArgs e ) { if (!Page.IsPostBack) { DataTabledt = new DataTable(); DataRow dr; dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32))); dt.Columns.Add(new DataColumn("StringValue", typeof(string))); dt.Columns.Add(new DataColumn("DateTimeMsec", typeof(Int32))); for (int i = 1; i <= 5; i++) { dr = dt.NewRow(); dr[0] = i; dr[1] = "Item " + i.ToString(); dr[2] = DateTime.Now.Millisecond; dt.Rows.Add(dr); }

  16. Example dgr.DataSource = new DataView(dt); dgr.DataBind(); } } </script> </head><body> <h3><font face="Verdana">Databinding to a DataView</font></h3> <form runat=server ID="f"> <asp:DataGrid id="dgr" runat="server" BorderColor="black" BorderWidth="1" GridLines="Both" CellPadding="3" CellSpacing="0" HeaderStyle-BackColor="#aaaadd“ /> </form> </body></html>

  17. Output • DataGrid is a data bound list control that displays the items from some data source in a table.

  18. Complex Data Binding • A complex data binding binds a list control (ListBox, DropDownList) or iterative control (Repeater) to one or more than one data element • typically more than one record in a database or to more than one of any other type of bindable data elements. • Records of data usually retrieved from some database. • The ASP.NET framework includes the ADO.NET data access technology for working with databases and other OLE DB data sources. • ADO is ActiveX Data Object. • ADO.NET is a set of classes to access and work with databases. • ADO.NET is an evolution of the ADO data access model of Microsoft.

  19. DB Connection Command DataSet Steps of data connection and data manipulations 3 steps should be done to retrieve some data from DB • A connection object created to represent a physical connection to some data store (an SQL Server or an XML file). • A command object created to represent a directive to retrieve from (select) or manipulate (insert, update, delete) the data store. • A dataset object created to represent the actual data. Note that DataSets are always disconnected from their source connection and data model and can be modified independently.

  20. Data Providers • In ADO.NET different namespaces and classes are created to work with different data providers: • System.Data.SqlClient – Microsoft SQL Server 7.0 or higher • System.Data.OleDb – OLE DB provider, such as Microsoft Access • System.Data.OracleClient – Oracle Database server. • In our course you will work with SQL Server using System.Data.SqlClient namespace.

  21. Database SqlConnection SqlCommand SqlDataReader System.Data.SqlClient • System.Data.SqlClient namespace includes 3 classes to perform data connection and data manipulation: • SqlConnection • SqlCommand • SqlDataReader

  22. Opening a connection • To work with SQL Server the following directive should be added to ASP.Net pages: • <%@ Import Namespace="System.Data.SqlClient" %> • The first step is to open a database connection. • SqlConnectionclass is used to establish a connection to SQL Server database. SqlConnection con; con=new SqlConnection("server=localhost;uid=sa;database=asp" ); con.open();

  23. SqlConnection • An SqlConnection class instance should be created (con=new SqlConnection()). • It is initialized by passing a connection string to the constructor of SqlConnection class. • The connection string should provide all necessary location and authentication information to connect to SQL server. server=localhost;uid=sa;pwd=secret;database=asp • where server=localhost (specifies a ServerName), uid=‘sa’ (specifies a user sa=server admin), pwd (specifies a password if required),Database=‘asp’ specifies the Database Name • Finally the connection is opened by calling an open() method - con.open().

  24. SqlCommand • An SqlCommand class represents an SQL statement (query) or a stored procedure. SqlCommand myCommand = new SqlCommand("select * from Table", con); • where a constructor specifies statement/query to perform and using which database connection. • Later this object uses an ExecuteReader() method to retrieve the result of the query. • The result may return non values (ExecuteNonQuery - update) or to return a single value (ExecuteScalar - count) or to return a DataReader(ExecuteReader). • If a record set is returned then it is stored in SqlDataReader object.

  25. Partial Example SqlConnection myConnection = new SqlConnection("server=localhost;uid=sa;database=asp"); SqlCommand myCommand = new SqlCommand( "UPDATE Table SET phone='(800) 555-5555' WHERE au_id = '123-45-6789'", myConnection); myCommand.Connection.Open(); myCommand.ExecuteNonQuery(); myCommand.Connection.Close();

  26. SqlDataReader • SqlDataReader class represents a stream of database records returned from a SQL statement (query) or a stored procedure. SqlDataReader dr = myCommand.ExecuteReader(); • It is a forward-only, read-only access to a set of rows returned from a SQL server database. • Later some control should update it’s DataSource property to this DataReader: MyDataGrid.DataSource = dr; MyDataGrid.DataBind();

  27. Final step • The final step do not forget • to close the DataReader: dr.Close(); • to close the Connection: con.Close();

  28. Example <%@ Page Language="C#"%> <%@ Import Namespace="System.Data.SqlClient" %> <script runat=server> void Page_Load(Object sender , EventArgs e) { SqlConnection con = new sqlConnection("Server=localhost;uid=sa;database=pubs"); con.Open(); SqlCommand cmd = new SqlCommand( "Select au_name From Authors", con ); SqlDataReader dtrAuthors = cmd.ExecuteReader(); while ( dtrAuthors.Read()) { Response.Write( "<li>" ); Response.Write( dtrAuthors[ "au_name" ] ); } dtrAuthors.Close(); con.Close(); }</script> Read method returns true if there is a next record to read Gets a value for the field called au_name

  29. Any Questions?

More Related