Download presentation
Presentation is loading. Please wait.
Published byGerald Moody Modified over 8 years ago
1
ASP.NET Part 4 Instructor: Charles Moen CSCI/CINF 4230
2
ADO.NET (Continued from last week)
3
3 Disconnected Data Access Fetch the data and store it in memory Steps to query the database with direct data access 1. Create Connection and Command objects 2. Create DataSet and DataAdapter objects 3. Retrieve information from the database with the DataAdapter object and add it to the DataSet object 4. Close the connection 5. Interact with the data in your code ASP.NET (MacDonald) using System.Data; using System.Data.OleDb; using System.Web.Configuration; In your C# code, import the correct ADO.NET namespaces
4
4 Deli Menu Demo ASP.NET (MacDonald) Use ASP.NET and Visual Studio 2008 to build a web application to display the results of a menu search by category using a DropDownList
5
5 Demo web.config ASP.NET (MacDonald) Define the connection string in the web.config file so that it is available throughout your application NOTE: This is a partial file. Points to the App_Data folder inside your web application directory The alias that you can use in your code
6
6 Demo Default.aspx.cs ASP.NET (MacDonald, Walther) using System; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.OleDb; using System.Web.Configuration; public partial class _Default : System.Web.UI.Page { private string connectionString = WebConfigurationManager.ConnectionStrings["Deli"].ConnectionString; private DataSet ds; Add a DataSet object The DataSet stores the data that was retrieved from the database, so it can be considered to be an in-memory database
7
7 Demo Page_Load ASP.NET (MacDonald) protected void Page_Load(object sender, EventArgs e) { string selectSql = "SELECT id, category FROM Categories "; OleDbConnection conn = new OleDbConnection(connectionString); OleDbCommand cmd = new OleDbCommand(selectSql, conn); OleDbDataAdapter adapter = new OleDbDataAdapter(cmd); ds = new DataSet(); try { conn.Open(); adapter.Fill(ds, "Categories"); } catch (Exception error) { resultsLabel.Text = "ERROR: " + error.Message; } finally { conn.Close(); } if (!IsPostBack) { foreach (DataRow row in ds.Tables["Categories"].Rows) { ListItem newItem = new ListItem(); newItem.Text = row["category"].ToString(); newItem.Value = row["id"].ToString(); categoriesDropDownList.Items.Add(newItem); } Create the DataSet and DataAdapter objects After storing the data in memory, close the connection Retrieve the data with the DataAdapter object and fill the DataSet object with it Then iterate through the data stored in memory to create the list The DataAdapter is the object that is used to transfer data from the physical database to the DataSet, the “in-memory” database
8
8 Demo Page_Load ASP.NET (MacDonald) protected void Page_Load(object sender, EventArgs e) { string selectSql = "SELECT id, category FROM Categories "; OleDbConnection conn = new OleDbConnection(connectionString); OleDbCommand cmd = new OleDbCommand(selectSql, conn); OleDbDataAdapter adapter = new OleDbDataAdapter(cmd); ds = new DataSet(); try { conn.Open(); adapter.Fill(ds, "Categories"); cmd.CommandText = "select * from MenuItems"; adapter.Fill(ds, "MenuItems"); } catch (Exception error) { resultsLabel.Text = "ERROR: " + error.Message; } finally { conn.Close(); } if (!IsPostBack) { foreach (DataRow row in ds.Tables["Categories"].Rows) { ListItem newItem = new ListItem(); newItem.Text = row["category"].ToString(); newItem.Value = row["id"].ToString(); categoriesDropDownList.Items.Add(newItem); } The DataSet object can hold multiple tables What if we want to use the data from both tables on this page?
9
9 Demo categoriesDropDownList_SelectedIndexChanged ASP.NET (MacDonald) protected void categoriesDropDownList_SelectedIndexChanged(object sender, EventArgs e) { if (IsPostBack) { StringBuilder sb = new StringBuilder(); sb.Append(" "); foreach (DataRow menuItemRow in ds.Tables["MenuItems"].Rows) { if (menuItemRow["category"].ToString() == categoriesDropDownList.SelectedValue) { sb.Append(" "); sb.Append(menuItemRow["item"].ToString()); sb.Append(" "); sb.Append(menuItemRow["description"].ToString()); sb.Append(" "); sb.Append(menuItemRow["price"].ToString()); sb.Append(" "); } sb.Append(" "); resultsLabel.Text = sb.ToString(); } An HTML table can be built by interacting with the data that is stored in memory inside the DataSet object
10
Data Binding
11
11 Data Binding Binding a control to a data source Single-value binding Inserted in almost any element in the aspx file Insert a variable, property, or expression into a page Repeated-value binding Works with ASP.NET list controls that support data binding Set the control properties DataBind() Method of the Page class Activates the data bindings, typically called in the Page_Load handler ASP.NET (MacDonald)
12
12 Single-Value Binding 1.Insert a data binding expression into the aspx code Could be a variable, property, or expression 2.Call DataBind() in the code ASP.NET (MacDonald) Opening and closing symbols A data binding expression
13
13 Single-Value Binding Example ASP.NET (MacDonald) Today is public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataBind(); } 2. Call DataBind() to see the output on the page 1.Insert a data binding expression into the aspx code
14
14 Some questions about single-value binding What are some problems with single-value binding? ANSWER: It mixes the code with the presentation layer instead of keeping it all in one place, inside the code-behind file What shows up on the page when you forget to call DataBind() ? What shows up on the page when the following data binding expression is used in the aspx code? ASP.NET (MacDonald) What would the URL look like?
15
15 Repeated-Value Binding 1.Create a data object, such as an ArrayList, and fill it with data 2.Link the data object to a control Some controls that support data binding: ListBox, DropDownList, CheckBoxList, RadioButtonList, HtmlSelect, GridView, FormView, ListView 3.Call DataBind() in the code ASP.NET (MacDonald)
16
16 Repeated-Value Binding Example ASP.NET (MacDonald) public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ArrayList categories = new ArrayList(); categories.Add("Sandwiches"); categories.Add("Salads"); categories.Add("Pasta"); categoriesDropDownList.DataSource = categories; DataBind(); } 1.Create a data object filled with data 2.Link the data object with the control – not necessary to use a loop to add the ListItems 3.Call DataBind() to see the output on the page Add a list control that supports data binding in the aspx code
17
17 Data Source Controls We can use data source controls to interact with a database without having to write the data access code SqlDataSource Connect to any data source that has an ADO.NET data provider AccessDataSource Connect to an Access database file ObjectDataSource XmlDataSource Connect to an XML file SiteMapDataSource ASP.NET (MacDonald)
18
18 Data Source Control Example ASP.NET (MacDonald) First, add the db.mdb file to the App_Data folder in Visual Studio Then, add the connection string to the web.config file
19
19 Data Source Control Example ASP.NET (MacDonald) <asp:SqlDataSource ID="sourceCategories" runat="server" /> Add a SqlDataSource control
20
20 Data Source Control Example ASP.NET (MacDonald) <asp:SqlDataSource ID="sourceCategories" runat="server" ProviderName="System.Data.OleDb" ConnectionString=" " /> Add the namespace for the correct provider as the value of the “ProviderName” property Use the alias of the connection string that you created in the web.config file To refer to a connection string in the aspx file, use this syntax
21
21 Data Source Control Example ASP.NET (MacDonald) <asp:SqlDataSource ID="sourceCategories" runat="server" ProviderName="System.Data.OleDb" ConnectionString=" " SelectCommand="select id, category from categories" /> The SQL command can be added as an inline string The SqlDataSource control can have one each of the following commands: SelectCommand InsertCommand UpdateCommand DeleteCommand (Although some controls do not support all operations)
22
22 Data Source Control Example ASP.NET (MacDonald) <asp:SqlDataSource ID="sourceCategories" runat="server" ProviderName="System.Data.OleDb" ConnectionString=" " SelectCommand="select id, category from categories" /> <asp:Label ID="categoriesLabel" runat="server" Text="Categories: " /> Add the label control
23
23 Data Source Control Example ASP.NET (MacDonald) <asp:SqlDataSource ID="sourceCategories" runat="server" ProviderName="System.Data.OleDb" ConnectionString=" " SelectCommand="select id, category from categories" /> <asp:Label ID="categoriesLabel" runat="server" Text="Categories: " /> <asp:DropDownList ID="categoriesDropDownList" runat="server" DataSourceID="sourceCategories" /> Add the DropDownList control Link the data object with the control using the “DataSourceID” property
24
24 Data Source Control Example ASP.NET (MacDonald) <asp:SqlDataSource ID="sourceCategories" runat="server" ProviderName="System.Data.OleDb" ConnectionString=" " SelectCommand="select id, category from categories" /> <asp:Label ID="categoriesLabel" runat="server" Text="Categories: " /> <asp:DropDownList ID="categoriesDropDownList" runat="server" DataSourceID="sourceCategories" DataTextField="category" DataValueField="id" /> Set the “DataTextField” property and the “DataValueField” property with the values of the fields specified in the query
25
25 Advantages of the Data Source Controls It was not necessary to write any C# code, such as creating the Connection, Command, and Reader objects; using try-catch-finally blocks; or using a loop to populate the list The control could have been added and configured by using Visual Studio features such as the Design view, the Toolbox, and the Properties editor ASP.NET (MacDonald)
26
26 Data Controls Rich data controls allow you to bind an entire table of data, using a Data Source Control GridView DetailsView FormView ASP.NET (MacDonald)
27
27 GridView Example ASP.NET (MacDonald) <asp:SqlDataSource ID="menuItemsSource" runat="server" ProviderName="System.Data.OleDb" ConnectionString=" " SelectCommand="select * from MenuItems" /> Add to your Web Site: The db.mdb file A connection string in web.config A SqlDataSource control in the aspx file
28
28 GridView Example ASP.NET (MacDonald) <asp:SqlDataSource ID="menuItemsSource" runat="server" ProviderName="System.Data.OleDb" ConnectionString=" " SelectCommand="select * from MenuItems" /> <asp:GridView ID="GridView1" runat="server" DataSourceID="menuItemsSource" /> Add the GridView control Bind it to the SqlDataSource
29
29 GridView Example ASP.NET (MacDonald) Change the GridView control in the Design view Auto Format... Edit Columns... Add New Column... Enable Paging Enable Sorting
30
Master Pages
31
31 Master Pages Used to define the layout of multiple pages in your web site Page templates are used to define features such as headers, footers, navigation panels Use the.master file extension Must be used with content pages which are inserted at the location of the ContentPlaceHolder controls Content pages Inserted into the master page layout Acquires the layout of the master page ASP.NET (MacDonald)
32
32 Master Page Example ASP.NET (MacDonald) To add a master page: 1.In the “Website” menu, select “Add New Item” 2.Select “Master Page” The master directive identifies the master page Content pages go into the ContentPlaceHolder
33
33 Master Page Example ASP.NET (MacDonald) Add elements to the master page outside of the ContentPlaceHolder.banner { font-family: Arial, Helvetica, sans-serif; background-color: #800000; color: #FFFFFF; font-weight: bold; padding: 5px; } Garden Fresh Sandwich Deli
34
34 Master Page Example ASP.NET (MacDonald) To add a content page: 1.In the “Website” menu, select “Add New Item” 2.Select “Web Form” 3.Check “Select master page” in the dialog The page directive connects it to the master page The Content element with the “head” id should contain styles or scripts that are specific to a particular content page The page content should be inserted into this Content element
35
35 Master Page Example ASP.NET (MacDonald) Sandwiches Salads Pasta
36
36 References MacDonald, Matthew, Beginning ASP.NET 3.5 in C# 2008: From Novice to Professional, Second Edition. Apress, 2007. Walther, Stephen. ASP.NET 3.5 Unleashed. SAMS, 2008.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.