SlideShare une entreprise Scribd logo
1  sur  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" />

Contenu connexe

Tendances

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Plus 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
 

Dernier

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Dernier (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

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" />