Your SlideShare is downloading. ×
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Chapter 15
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Chapter 15

1,037

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,037
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
35
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. • Introducing Data Binding• Types of ASP.NET Data Binding • Simple-Value • Repeated-Value• How Data Binding Works• A Simple Data Binding Example• Data Binding with ADO.NET• Data Source Controls• How Data Source Controls Work
  • 2. The process of popping data directlyinto HTML elements and fully formattedcontrols is called data binding.
  • 3. You can use single-value data binding to add informationanywhere on an ASP.NET page.Single-value data binding allows you to take a variable, aproperty, or an expression and insert it dynamically into apage.To use single-value binding, you must insert a databinding expression into the markup in the .aspx file (notthe code-behind file).
  • 4. In .aspx file<asp:Label id="lblDynamic" runat="server" Font-Size="X-Large">There were <%# TransactionCount %> transactions today.I see that you are using <%# Request.Browser.Browser %></asp:Label> In .cs file protected void Page_Load(object sender, EventArgs e) { // to look up a value for TransactionCount TransactionCount = 10; // Now convert all the data binding expressions on the page. this.DataBind(); }
  • 5. public partial class DataBindingUrl : System.Web.UI.Page{protected string URL;protected void Page_Load(Object sender, EventArgs e){URL = "Images/picture.jpg";this.DataBind();}}<asp:Label id="lblDynamic" runat="server"><%# URL %></asp:Label><asp:CheckBox id="chkDynamic" Text="<%# URL %>"runat="server" /><asp:Hyperlink id="lnkDynamic" Text="Click here!" NavigateUrl="<%#URL %>"runat="server" />
  • 6. Repeated-value data binding works with the ASP.NETlist controls (and the rich data controls described in thenext chapter).To use repeated-value binding, you link one of thesecontrols to a datasource (such as a field in a data table).When you call DataBind(), the control automaticallycreates a full list using all the corresponding values.This saves you from writing code that loops through thearray ordata table and manually adds elements to acontrol
  • 7. To create a data expression for list binding, you need to usea list control that explicitly supports data binding. :ListBox, DropDownList, CheckBoxList, and RadioButtonList:These web controls provide a list for a single field ofinformation.HtmlSelect: This server-side HTML control represents theHTML <select> element and works essentially the sameway as the ListBox web control. Generally, you’ll use thiscontrol only for backward compatibility.GridView, DetailsView, FormView, and ListView: These richweb controls allow you to provide repeating lists or grids thatcan display more than one field of information at a time.
  • 8. ArrayList fruit = new ArrayList();fruit.Add("Kiwi");fruit.Add("Pear");fruit.Add("Mango");Now, you can link this collection to the ListBox control:lstItems.DataSource = fruit;this.DataBind();
  • 9. List<string> fruit = new List<string>();fruit.Add("Kiwi");fruit.Add("Pear");fruit.Add("Mango");fruit.Add("Blueberry");// Define the binding for the list controls.MyListBox.DataSource = fruit;MyDropDownListBox.DataSource = fruit;MyHtmlSelect.DataSource = fruit;MyCheckBoxList.DataSource = fruit;MyRadioButtonList.DataSource = fruit;// Activate the binding.this.DataBind();
  • 10. <select name="MyListBox" id="MyListBox" ><option value="1">Kiwi</option><option value="2">Pear</option><option value="3">Mango</option></select>protected void MyListBox_SelectedIndexChanged(Objectsender,EventArgs e){lblMessage.Text = "You picked: " +MyListBox.SelectedItem.Text;lblMessage.Text += " which has the key: " +MyListBox.SelectedItem.Value;}
  • 11. string selectSQL = "SELECT ProductName, ProductID FROM Products";SqlConnection con = new SqlConnection(connectionString);SqlCommand cmd = new SqlCommand(selectSQL, con);// Open the connection.con.Open();// Define the binding for the drop down list.lstProduct.DataSource = cmd.ExecuteReader();lstProduct.DataTextField = "ProductName";lstProduct.DataValueField = "ProductID";// Activate the binding.this.DataBind();con.Close();// Make sure nothing is currently selected in the list box.lstProduct.SelectedIndex = -1;
  • 12. 1. First, create the DataSet.2. Next, create a new DataTable, and add it to the DataSet.Tables collection.3. Next, define the structure of the table by adding DataColumn objects (one foreach field) to the DataTable.Colums collection.4. Finally, supply the data. You can get a new, blank row that has the same structure as your DataTable by calling the DataTable.NewRow() method. You must then set the data in all its fields, and add the DataRow to the DataTable.Rows collection.
  • 13. Data source controls allow you to create data-bound pageswithout writing any data access code at all. •SqlDataSource: This data source allows you to connect to any data source that has an ADO.NET data provider. When using this data source, you don’t need to write the data access code. • AccessDataSource: This data source allows you to read and write the data in an Access database file (.mdb). •ObjectDataSource: This data source allows you to connect to a custom data access class. This is the preferred approach for large-scale professional web applications, but it forces you to write much more code. • XmlDataSource: This data source allows you to connect to an XML file. You’ll learn more about XML in Chapter 18. • SiteMapDataSource: This data source allows you to connect to a .sitemap file that describes the navigational structure of your website. • EntityDataSource: This data source allows you to query a database using the LINQ to Entities feature, which you’ll tackle in Chapter 24. • LinqDataSource: This data source allows you to query a database using the LINQ to SQL feature, which is a similar (but somewhat less powerful) predecessor to LINQ to Entities.
  • 14. The SqlDataSource represents a database connection that uses anADO.NET provider. This includes SQL Server, Oracle, and OLE DB orODBC data sources..NET includes a data provider factory for each of its four data providers:• System.Data.SqlClient• System.Data.OracleClient• System.Data.OleDb• System.Data.OdbcYou can use all of these providers with the SqlDataSource.<asp:SqlDataSource ProviderName="System.Data.SqlClient" ... />Technically, you can omit this piece of information, because theSystem.Data.SqlClient provider factory is the default.
  • 15. <configuration><connectionStrings><add name="Northwind" connectionString="Data Source=localhostSQLEXPRESS;InitialCatalog=Northwind;Integrated Security=SSPI" /></connectionStrings>...</configuration><asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:Northwind %>" ... />
  • 16. You can use each SqlDataSource control you create,to retrieve a single query.The SqlDataSource command logic is supplied throughfour properties—SelectCommand, InsertCommand, UpdateCommand, andDeleteCommand—each of which takes a string.<asp:SqlDataSource ID="sourceProducts" runat="server"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT ProductName, ProductIDFROM Products“ />
  • 17. <asp:SqlDataSource ID="sourceProductDetails" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>“SelectCommand="SELECT * FROM Products WHEREProductID=@ProductID"/><asp:SqlDataSource ID="sourceProductDetails" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT * FROM Products WHEREProductID=@ProductID"><SelectParameters><asp:ControlParameter ControlID="lstProduct" Name="ProductID"PropertyName="SelectedValue" /></SelectParameters></asp:SqlDataSource>
  • 18. If bound to Rich Controls SqlDataSource can displaymany fields at a time as compared to List Controls whichdisplay only one field at a time.Example:GridviewDetailsView
  • 19. For example, you could split the earlier example into two pages. In the firstpage, define a list control that shows all the available products:<asp:SqlDataSource ID="sourceProducts" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT ProductName, ProductID FROM Products"/><asp:DropDownList ID="lstProduct" runat="server" AutoPostBack="True"DataSourceID="sourceProducts" DataTextField="ProductName"DataValueField="ProductID" />
  • 20. protected void cmdGo_Click(object sender, EventArgs e){if (lstProduct.SelectedIndex != -1){Response.Redirect("QueryParameter2.aspx?prodID=" + lstProduct.SelectedValue);}}Finally, the second page can bind the DetailsView according to the ProductID valuethat’s supplied in the query string:<asp:SqlDataSource ID="sourceProductDetails" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT * FROM Products WHERE ProductID=@ProductID"><SelectParameters><asp:QueryStringParameter Name="ProductID" QueryStringField="prodID" /></SelectParameters></asp:SqlDataSource><asp:DetailsView ID="detailsProduct" runat="server"DataSourceID="sourceProductDetails" />

×