SlideShare una empresa de Scribd logo
1 de 21
• 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
The process of popping data directly
into HTML elements and fully formatted
controls is called data binding.
You can use single-value data binding to add information
anywhere on an ASP.NET page.

Single-value data binding allows you to take a variable, a
property, or an expression and insert it dynamically into a
page.

To use single-value binding, you must insert a data
binding expression into the markup in the .aspx file (not
the code-behind file).
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();
 }
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" />
Repeated-value data binding works with the ASP.NET
list controls (and the rich data controls described in the
next chapter).

To use repeated-value binding, you link one of these
controls to a datasource (such as a field in a data table).
When you call DataBind(), the control automatically
creates a full list using all the corresponding values.

This saves you from writing code that loops through the
array ordata table and manually adds elements to a
control
To create a data expression for list binding, you need to use
a list control that explicitly supports data binding. :

ListBox, DropDownList, CheckBoxList, and RadioButtonList:
These web controls provide a list for a single field of
information.

HtmlSelect: This server-side HTML control represents the
HTML <select> element and works essentially the same
way as the ListBox web control. Generally, you’ll use this
control only for backward compatibility.

GridView, DetailsView, FormView, and ListView: These rich
web controls allow you to provide repeating lists or grids that
can display more than one field of information at a time.
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();
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();
<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(Object
sender,
EventArgs e)
{
lblMessage.Text = "You picked: " +
MyListBox.SelectedItem.Text;
lblMessage.Text += " which has the key: " +
MyListBox.SelectedItem.Value;
}
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;
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.
Data source controls allow you to create data-bound pages
without 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.
The SqlDataSource represents a database connection that uses an
ADO.NET provider. This includes SQL Server, Oracle, and OLE DB or
ODBC 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.Odbc
You can use all of these providers with the SqlDataSource.

<asp:SqlDataSource ProviderName="System.Data.SqlClient" ... />

Technically, you can omit this piece of information, because the
System.Data.SqlClient provider factory is the default.
<configuration>
<connectionStrings>
<add name="Northwind" connectionString=
"Data Source=localhostSQLEXPRESS;Initial
Catalog=Northwind;Integrated Security=SSPI" />
</connectionStrings>
...
</configuration>


<asp:SqlDataSource ConnectionString=
"<%$ ConnectionStrings:Northwind %>" ... />
You can use each SqlDataSource control you create,
to retrieve a single query.

The SqlDataSource command logic is supplied through
four properties—
SelectCommand, InsertCommand, UpdateCommand, and
DeleteCommand—each of which takes a string.

<asp:SqlDataSource ID="sourceProducts" runat="server"
ConnectionString="<%$ ConnectionStrings:Northwind %>"
SelectCommand="SELECT ProductName, ProductID
FROM Products“ />
<asp:SqlDataSource ID="sourceProductDetails" runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$ ConnectionStrings:Northwind %>“

SelectCommand="SELECT * FROM Products WHERE
ProductID=@ProductID"/>

<asp:SqlDataSource ID="sourceProductDetails" runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$ ConnectionStrings:Northwind %>"
SelectCommand="SELECT * FROM Products WHERE
ProductID=@ProductID">

<SelectParameters>
<asp:ControlParameter ControlID="lstProduct" Name="ProductID"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
If bound to Rich Controls SqlDataSource can display
many fields at a time as compared to List Controls which
display only one field at a time.

Example:

Gridview
DetailsView
For example, you could split the earlier example into two pages. In the first
page, 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" />
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 value
that’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" />

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Ado.net
Ado.netAdo.net
Ado.net
 
Database programming in vb net
Database programming in vb netDatabase programming in vb net
Database programming in vb net
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
Database Connection
Database ConnectionDatabase Connection
Database Connection
 
Ado.net
Ado.netAdo.net
Ado.net
 
5.C#
5.C#5.C#
5.C#
 
Ado.net
Ado.netAdo.net
Ado.net
 
ADO CONTROLS - Database usage
ADO CONTROLS - Database usageADO CONTROLS - Database usage
ADO CONTROLS - Database usage
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.Net
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Databind in asp.net
Databind in asp.netDatabind in asp.net
Databind in asp.net
 
VISUAL BASIC .net data accesss vii
VISUAL BASIC .net data accesss viiVISUAL BASIC .net data accesss vii
VISUAL BASIC .net data accesss vii
 
Ado Net
Ado NetAdo Net
Ado Net
 
Ado.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworksAdo.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworks
 

Similar a Chapter 15

Introduction to ado
Introduction to adoIntroduction to ado
Introduction to adoHarman Bajwa
 
Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net ArchitectureUmar Farooq
 
Disconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETDisconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETEverywhere
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Csharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxCsharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxfacebookrecovery1
 
WEB PROGRAMMING USING ASP.NET
WEB PROGRAMMING USING ASP.NETWEB PROGRAMMING USING ASP.NET
WEB PROGRAMMING USING ASP.NETDhruvVekariya3
 
Marmagna desai
Marmagna desaiMarmagna desai
Marmagna desaijmsthakur
 
Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.Alexey Furmanov
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
Datasource in asp.net
Datasource in asp.netDatasource in asp.net
Datasource in asp.netSireesh K
 
ADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaSonu Vishwakarma
 

Similar a Chapter 15 (20)

Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Ado.net
Ado.netAdo.net
Ado.net
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to ado
 
Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net Architecture
 
Disconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETDisconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NET
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Csharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxCsharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptx
 
Ado
AdoAdo
Ado
 
WEB PROGRAMMING USING ASP.NET
WEB PROGRAMMING USING ASP.NETWEB PROGRAMMING USING ASP.NET
WEB PROGRAMMING USING ASP.NET
 
Marmagna desai
Marmagna desaiMarmagna desai
Marmagna desai
 
Asp.Net Database
Asp.Net DatabaseAsp.Net Database
Asp.Net Database
 
2310 b 09
2310 b 092310 b 09
2310 b 09
 
Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Datasource in asp.net
Datasource in asp.netDatasource in asp.net
Datasource in asp.net
 
Introduction to ado.net
Introduction to ado.netIntroduction to ado.net
Introduction to ado.net
 
ADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaADO .NET by Sonu Vishwakarma
ADO .NET by Sonu Vishwakarma
 
Ado
AdoAdo
Ado
 

Más de application developer (20)

Chapter 26
Chapter 26Chapter 26
Chapter 26
 
Chapter 25
Chapter 25Chapter 25
Chapter 25
 
Chapter 23
Chapter 23Chapter 23
Chapter 23
 
Assignment
AssignmentAssignment
Assignment
 
Next step job board (Assignment)
Next step job board (Assignment)Next step job board (Assignment)
Next step job board (Assignment)
 
Chapter 19
Chapter 19Chapter 19
Chapter 19
 
Chapter 18
Chapter 18Chapter 18
Chapter 18
 
Chapter 17
Chapter 17Chapter 17
Chapter 17
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
 
Week 3 assignment
Week 3 assignmentWeek 3 assignment
Week 3 assignment
 
Chapter 13
Chapter 13Chapter 13
Chapter 13
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
Chapter 10
Chapter 10Chapter 10
Chapter 10
 
C # test paper
C # test paperC # test paper
C # test paper
 
Chapter 9
Chapter 9Chapter 9
Chapter 9
 
Chapter 8 part2
Chapter 8   part2Chapter 8   part2
Chapter 8 part2
 
Chapter 8 part1
Chapter 8   part1Chapter 8   part1
Chapter 8 part1
 
Chapter 7
Chapter 7Chapter 7
Chapter 7
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 

Último

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 

Último (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 

Chapter 15

  • 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 directly into HTML elements and fully formatted controls is called data binding.
  • 3. You can use single-value data binding to add information anywhere on an ASP.NET page. Single-value data binding allows you to take a variable, a property, or an expression and insert it dynamically into a page. To use single-value binding, you must insert a data binding expression into the markup in the .aspx file (not the 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.NET list controls (and the rich data controls described in the next chapter). To use repeated-value binding, you link one of these controls to a datasource (such as a field in a data table). When you call DataBind(), the control automatically creates a full list using all the corresponding values. This saves you from writing code that loops through the array ordata table and manually adds elements to a control
  • 7. To create a data expression for list binding, you need to use a list control that explicitly supports data binding. : ListBox, DropDownList, CheckBoxList, and RadioButtonList: These web controls provide a list for a single field of information. HtmlSelect: This server-side HTML control represents the HTML <select> element and works essentially the same way as the ListBox web control. Generally, you’ll use this control only for backward compatibility. GridView, DetailsView, FormView, and ListView: These rich web controls allow you to provide repeating lists or grids that can 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(Object sender, 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 pages without 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 an ADO.NET provider. This includes SQL Server, Oracle, and OLE DB or ODBC 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.Odbc You can use all of these providers with the SqlDataSource. <asp:SqlDataSource ProviderName="System.Data.SqlClient" ... /> Technically, you can omit this piece of information, because the System.Data.SqlClient provider factory is the default.
  • 15. <configuration> <connectionStrings> <add name="Northwind" connectionString= "Data Source=localhostSQLEXPRESS;Initial Catalog=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 through four properties— SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand—each of which takes a string. <asp:SqlDataSource ID="sourceProducts" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>" SelectCommand="SELECT ProductName, ProductID FROM Products“ />
  • 17. <asp:SqlDataSource ID="sourceProductDetails" runat="server" ProviderName="System.Data.SqlClient" ConnectionString="<%$ ConnectionStrings:Northwind %>“ SelectCommand="SELECT * FROM Products WHERE ProductID=@ProductID"/> <asp:SqlDataSource ID="sourceProductDetails" runat="server" ProviderName="System.Data.SqlClient" ConnectionString="<%$ ConnectionStrings:Northwind %>" SelectCommand="SELECT * FROM Products WHERE ProductID=@ProductID"> <SelectParameters> <asp:ControlParameter ControlID="lstProduct" Name="ProductID" PropertyName="SelectedValue" /> </SelectParameters> </asp:SqlDataSource>
  • 18. If bound to Rich Controls SqlDataSource can display many fields at a time as compared to List Controls which display only one field at a time. Example: Gridview DetailsView
  • 19.
  • 20. For example, you could split the earlier example into two pages. In the first page, 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" />
  • 21. 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 value that’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" />