


























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
It was developed by Microsoft to allow programmers to build dynamic web sites, applications and services. The name stands for Active Server Pages Network Enabled Technologies. ASP.NET (software) Developer(s) Microsoft.
Typology: Lecture notes
1 / 34
This page cannot be seen from the preview
Don't miss anything!
Database accessing on Web Applications : Data Binding Concept with Web – Creating Data
Grid – Binding Standard Web Server Controls– Display Data on Web Form using Data Bound Controls
Data Binding Concept with Web
Every ASP.NET web form control inherits the DataBind method from its parent Control class, which gives it an inherent capability to bind data to at least one of its properties. This is known as simple data binding or inline data binding. Simple data binding involves attaching any collection (item collection) which implements the IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the control. On the other hand, some controls can bind records, lists, or columns of data into their structure through a DataSource control. These controls derive from the BaseDataBoundControl class. This is called declarative data binding. The data source controls help the data-bound controls implement functionalities such as, sorting, paging, and editing data collections. The BaseDataBoundControl is an abstract class, which is inherited by two more abstract classes:
DataBoundControl HierarchicalDataBoundControl The abstract class DataBoundControl is again inherited by two more abstract classes:
ListControl CompositeDataBoundControl The controls capable of simple data binding are derived from the ListControl abstract class and these controls are:
BulletedList CheckBoxList DropDownList ListBox RadioButtonList The controls capable of declarative data binding (a more complex data binding) are derived from the abstract class CompositeDataBoundControl. These controls are:
DetailsView
FormView GridView RecordList
Simple Data Binding
Simple data binding involves the read-only selection lists. These controls can bind to an array list or fields from a database. Selection lists takes two values from the database or the data source; one value is displayed by the list and the other is considered as the value corresponding to the display. Let us take up a small example to understand the concept. Create a web site with a bulleted list and a SqlDataSource control on it. Configure the data source control to retrieve two values from your database (we use the same DotNetReferences table as in the previous chapter). Choosing a data source for the bulleted list control involves:
Selecting the data source control Selecting a field to display, which is called the data field Selecting a field for the value
When the application is executed, check that the entire title column is bound to the bulleted list and displayed.
Consider the following example to demonstrate the declarative data binding
Code:
The DataGrid Web server control is a multi-column, data-bound grid. Columns can be made that displays and edit data. Multi-columns include Edit, Update, Cancel, Select buttons, Custom Buttons, and Template Columns. Therefore Template Columns canbe laid further in Template-Editing Mode. The DataGrid control displays the fields of a data source as columns in a table. Each row in the control represents a record in the data source. The control supports selection, editing, deleting, paging, and sorting. The DataGrid control with strong features is the most complicated control included within the ASP.NET framework. Like the Repeater and DataList controls, it enables to format and display records from a database table. However, it has several advanced features, such as support for sorting and paging through records, which makes it unique. Records can be displayed in a DataGrid without using templates. A data source can be simply bound to the DataGrid, and it automatically displays the records. By default, a DataGrid displays gridlines around its items. Modification of the Grid line appearance can be done by setting the GridLines property. The possible values are Both, Horizontal, None, or Vertical. For example, to completely disable GridLines, the DataGrid would look like this: -
Create Table for Database and Name it as UserData
<asp:DataGrid
GridLines="None"
Runat="Server" />
To bind data to a data bound control, like gridview there are 2 ways
1. Without using data-source controls 2. Using data-source controls
If we are not using data source controls, then we have to write code to
1. Read connection string 2. Create connection object 3. Create SQL Command object 4. Execute the command 5. Retrieve and bind the results to the data-bound control.
Code to bind data to a gridview control, without using data-source controls:
string cs = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("Select * from tblProducts", con); con.Open(); GridView1.DataSource = cmd.ExecuteReader(); GridView1.DataBind();
}
If we are using data source controls , we don't have to write even a single line of code. All, you
have to do is, drag and drop a data-source control on the webform. Configure the data-source
control to connect to a data source and retrieve data. Finally associate the data-source control, to a data-bound control using "DataSourceID" property.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>" SelectCommand="SELECT * FROM [tblProducts]">
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1">
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" /> </asp:GridView>
1. "ConnectionString" property of the "SqlDataSource" control is used to determine the
database it has to connect, to retrieve data
2. "SelectCommand" property specifies the command that needs to be executed. 3. DataSource control is associated, with the gridview control, using "DataSourceID" property
of the GridView control.
All databound controls has DataSourceID property. A few examples of databound controls
include
Fig : GridView
control. Let's now take a detailed look at all of the standard controls used in ASP.NET.
Repeater Control
The Repeater control is a Data Bind Control, also known as container controls. The Repeater control is used to display a repeated list of items that are bound to the control. This control may be bound to a database table, an XML file, or another list of items. It has no built-in layout or styles, so you must explicitly declare all layout, formatting and style tags within the controls templates. You would require writing an explicit code to do paging using this control. The Repeater repeats a layout of HTML you write, it has the least functionality of the rest of the three controls.
The Repeater control supports the following features:
List format No default output More control and complexity Item as row Paging, Sorting and Grouping requires custom code writing only Web control that allows you to split markup tags across the templates no built-in selection capabilities no built-in support for edit, insert and delete capabilities no built-in support for paging, sorting and grouping capabilities no built-in layout or styles, need to declare all layout, formatting and style tags explicitly within the control's templates Strictly emits the markup specified in its templates, nothing more and nothing less.
Using the data we stored in table Student of our sample database, the Repeater control will look like this.
DataList Control
The DataList control renders data as a table and enables you to display data records in various layouts, such as ordering them in columns or rows. You can configure the DataList control to enable users to edit or delete a record in the table. We can use a DataList control where we need a single-column list. The DataList control works like the Repeater control, used to display the data in a repeating structure, such as a table. It displays data in a format that you can define using a template and styles.The DataList control does not automatically use a data source control to edit data. Instead, it provides command events in which you can write your own code for these scenarios. You can configure the DataList control where the user can edit or delete a record in the table.
The DataList control supports the following features:
Support for binding data source controls such as SqlDataSource, LinqDataSource and ObjectDataSource Directional rendering Good for columns Item as cell Updatable Control over Alternate item Paging function needs handwriting. After execution our ListView will look like this.
ListView Control
The ListView control was introduced with ASP.NET 3.5. The ListView control resembles the GridView control. The only difference between them is that the ListView control displays data using user-defined templates instead of row fields. Creating your own templates gives you more flexibility in controlling how the data is displayed. It enables you to bind to data items that are returned from a data source and display them. The data can be displayed in pages where you can display items individually, or you can group them. The template contains the formatting, controls and binding expressions that are used to lay out the data.
The ListView control supports the following features:
Binding to data source controls Customizable appearance through user-defined templates and styles. Built-in sorting and grouping capabilities Built-in insert, edit and delete capabilities Support for paging capabilities using a DataPager control. Built-in item selection capabilities Multiple key fields Programmatic access to the ListView object model to dynamically set properties, handle events and so on Fast performance as compared to GridView
Repeater vs. DataList vs. GridView vs. ListView
The common problem of using a GridView is a large ViewState that could cause slow page loads. Default GridView paging opens a complete data set in the server's memory. For large tables or for high traffic websites, this will overload the web server's resources. Even the DataPager control of a ListView still opens all the records in memory. Also, pages are opened using JavaScript. That means only the first page is indexed by search engines. The solution could be to create a custom pager, but this takes time to create, test and optimize code, as well as later maintenance of a separate project. The ListView control can exceed the capabilities of a Repeater or DataList control, but GridView still has the advantage of faster implementation and short markup code. Now for the second group. Here is the description of the two controls DetailsView and FormView.
DetailsView control
The DetailsView control is often used in master-detail scenarios where the selected record in a master control determines the record to display in the DetailsView control. It shows the details for the row in a separate space. We can customize the appearance of the DetailsView control using its style properties. Alternatively, we can also use Cascading Style Sheets (CSS) to provide styles to a DetailsView control. A DetailsView control appears as a form of recording and is provided by multiple records as well as insert, update and delete record functions.
The DetailsView control supports the following features:
Tabular rendering Supports column layout, by default two columns at a time Optional support for paging and navigation. Built-in support for data grouping
DetailsView vs. FormView Control
The DetailsView and FormView controls enable us to display a single data item, in ohter words a single database record at a time. Both controls enable the display, edit, insert and deletion of data items such as database records but with the requirement of a single data item at a time. Each of these two controls render the user interface in its own unique way. Compared to the DetailsView control, the FormView control gives more flexibility over the rendering of fields. This form of rendering data enables more control over the layout of the fields. Using the FormView control is more complex as compared to the DetailsView control.
Summary:
protected void Page_Load(object sender, EventArgs e) { FillDropDownList(); }
protected void chkPost_CheckedChanged(object sender, EventArgs e) { if (ddEmployee.SelectedValue != "0") { Response.Redirect("page.aspx?UserId=" & ddEmployee.SelectedValue.Trim()); } }
private void FillDropDownList() { try { SqlConnection con = new SqlConnection("server=localhost;database=Northwind;uid=sa;password=secret;"); con.Open(); SqlDataAdapter dap = new SqlDataAdapter("SELECT userid, username FROM table1", con); DataSet ds = new DataSet(); dap.Fill(ds); con.Close();
ddEmployee.DataSource = ds.Tables[ 0 ].DefaultView; ddEmployee.DataTextField = "username"; ddEmployee.DataValueField = "userid"; ddEmployee.DataBind();
Several controls in ASP.NET provide basic, list-based data binding. These controls are not meant to work with pages of data or provide elaborate editing scenarios. Instead, they allow you to provide a list of data items with which a user can operate. It shows these simple data- bound controls, including their common base class, ListControl.
Fig The ListControl class hierarchy.
The ListControl class is an abstract base class that provides common functionality for the classes that derive from it. This functionality includes an Items collection, which is a collection of ListItem data objects. Each ListItem object contains a Text property that is displayed to the user and a Value property that is posted back to the web server.
You can add items to the ListItems collection in code or declaratively in markup. You can also bind data to the controls that inherit from ListControl by setting the DataSource property (or the DataMember property if the source data has more than one table). You can also declaratively data-bind a ListControl-derived object by setting the DataSourceID property to the ID of a valid data source control on your page.
<asp:ListBox ID="ListBox1" runat="server" DataSourceID="SqlDataSource1" DataTextField="CompanyName" DataValueField="ShipperID"> </asp:ListBox>
The SelectedIndex property lets you get or set the index of the selected item in the ListControl. By using the SelectedItem property, you can access the selected ListItem object’s properties. If you only need to access the value of the selected ListItem, use the SelectedValue property.
The ListControl also contains the property called AppendDataBoundItems, which can be set to true to keep all items that are currently in the ListControl, in addition to appending the items from the data binding. Setting this property to false clears the Items property prior to binding the data.
The ListControl also provides the SelectedIndexChanged event, which is raised when the selection in the list control changes between posts to the server. Recall that you need to set a control’s AutoPostback property to true if you intend it to post back to the server for this type of event.
The DropDownList Control
The DropDownList control is used to display a list of items to users to allow them to make a single selection. The Items collection contains the child ListItem objects that are displayed in the DropDownList control. To determine the item that the user has selected, you can retrieve the SelectedValue, SelectedItem, or SelectedIndex property.
In the following example, a DropDownList control is bound to a SqlDataSource control that returns data from the Territories database table in the Northwind database. Notice that the DataTextField and DataValueField attributes are set to fields in the database table.
<asp:DropDownList runat="server" Width="250px"