Chapter 3: Data Controls


Overview

Data is at the heart of all applications. Granted, there are exceptions to this statement, but more often than not, Web applications are used for viewing, searching, and updating data. In this chapter, we’ll look at the features of ASP.NET that focus on binding user interface elements to data. Because binding to records from a sample database would unnecessarily complicate our sample code and detract from the focus on data controls, we create small datasets where appropriate directly in the page and bind to them. In practice, of course, your data would be retrieved from calls to middle-tier business objects or by accessing a back-end database directly.

Connecting data to server controls is referred to as data-binding. In Code Listing 3-1, we data-bind to a field declared on the page. In the Page_Load method, we set the theTime variable to the current time and then call the DataBind method on the page. Note the <%# syntax (it is not censored text) prior to the variable name. This code sequence is an indicator to ASP.NET that what follows is code that the ASP.NET page parser will inject into the page. That code—called a data-binding expression—is then called when the DataBind operation is performed on the page.

Code Listing 3-1: DataBindField.aspx

start example
 <script language="C#" runat="server">
DateTime theTime;
protected void Page_Load(object o, EventArgs e) {
theTime = DateTime.Now;
Page.DataBind();
}
</script>
The time is: <%# theTime %><br/>
end example

Figure 3-1 shows part of the code that ASP.NET generates for Code Listing 3-1. (Remember that this code is automatically generated and is not guaranteed to be consistent between versions of ASP.NET.) When DataBindField.aspx is executed, the BuildControlTree method is called. This method calls another automatically generated method (which has a mangled name) to build the data- bound string, which is accomplished using an instance of the DataBoundLiteralControl class. This method attaches an event handler to the newly created DataBoundLiteralControl for the DataBinding event. The Page_Load method calls the DataBind method, which then invokes this event handler code. The event handler calls the SetDataBoundString method on the original DataBoundLiteralControl to get the value of the field being used. The Text property of DataBoundLiteralControl is finally set to the field’s value, which is displayed when the control is rendered.

click to expand
Figure 3-1: Code generated for data-binding a page field

To display a simple value, the automatically generated code for the simple ASPX page shown in Code Listing 3-1 must seem like overkill. After all, we’re already writing code to set the value for the field, and it’s trivial to add another line to set the Text property of a control directly.

We can begin to see more power in the databinding construct in Code Listing 3-2. In this example, the expression is expanded to include values from two server controls on the page. Because we are assuming that the controls are integers, we really should validate the datatype, as discussed in Chapter 2.

Code Listing 3-2: DataBindControlValue.aspx

start example
 <script runat="server" language="C#">
protected void Page_Load(object o, EventArgs e) {
if(IsPostBack) {
Page.DataBind();
}
}
</script>
<form runat="server">
Add two numbers:
<asp:TextBox runat="server" /> +
<asp:TextBox runat="server" /><br />
<asp:Button type="submit" runat="server" Text="Submit" /><br />
The DataBound result =
<%# Int32.Parse(operand1.Text) + Int32.Parse(operand2.Text) %>
</form>
end example

Code Listing 3-2 shows that data-binding offers a shortcut for simple coding expressions or method invocations. You don’t have to declare a server control explicitly, provide code elsewhere to collect the values from the sources, and then assign the result. Instead, the data-binding support allows us to easily declare the expression inline. Notice that the Page_Load method in the example performs the DataBind operation only when the page is a postback. Because we provide no default values for the textbox controls, we wait until the user has had a chance to post their inputs. Often, the scenario is reversed and the data-bind operation is performed only when the request is not a postback. When a control can carry the data it is bound to between requests in ViewState, you can avoid performing expensive calculations or database operations again.

Tip

Use data-binding to declaratively control the display of values combined from the value of other controls.

Code Listing 3-3 demonstrates how data-binding also supports invoking methods automatically. In this example, input is gathered from the user. The use of validators assures us that some value has been provided and that it is a positive number and sufficiently small to calculate its factorial quickly. The data-binding expression is code to invoke the CalculateFactorial method. The CalculateFactorial method expects an integer type and returns a double, so the data-binding expression takes care of the type conversions to and from the string.

Code Listing 3-3: DataBindMethod.aspx

start example
 <script runat="server" language="C#">
protected void Page_Load(object o, EventArgs e) {
if(IsPostBack) {
Page.DataBind();
}
}
protected double CalculateFactorial(int input) {
double result = 1;
for(;input > 0; input--) {
result *= input;
}
return result;
}
</script>
<form runat="server">
Databind the result of a method call.
<asp:Textbox runat="server" /><br/>
<asp:RequiredFieldValidator runat="server"
ControlToValidate="theInput"
ErrorMessage="input is required" />
<asp:RangeValidator runat="server"
ControlToValidate="theInput"
ErrorMessage="input must be >= 0 and < 20"
Type="integer" MinimumValue="0" MaximumValue="20" /><br/>
<asp:Button runat="server" type="submit"
Text="Calculate Factorial" /><br/>
The result is: <b>
<%# CalculateFactorial(Int32.Parse(theInput.Text)).ToString() %>
</b>
</form>
end example

In Chapter 2, we said that the items of the list controls could be set declaratively, dynamically, or by using data-binding. When you data-bind the list controls, the data source you specify must support at least one of a set of interfaces. If the data source does not implement IEnumerable or IlistSource, an exception will be thrown. In Code Listing 3-4, we convert the DropDownList sample from Chapter 2 to bind to an ArrayList.

Code Listing 3-4: DataBindDropDownList.aspx

start example
 <script language="C#" runat="server">
protected void Page_Load(object o, EventArgs e) {
if(!IsPostBack) {
ArrayList arrayList = new ArrayList();
arrayList.Add("C#");
arrayList.Add("VB.NET");
arrayList.Add("JScript.Net");

languageDropDownList.DataSource = arrayList;
languageDropDownList.DataBind();

favoriteLanguage.Text
= languageDropDownList.SelectedItem.Value;
}
}

protected void DropDownListSelectionChanged(object o, EventArgs e) {
favoriteLanguage.Text = languageDropDownList.SelectedItem.Text;
}
</script>
<form runat="server">
<asp:DropDownList runat="server"
OnSelectedIndexChanged="DropDownListSelectionChanged" >
</asp:DropDownList><br/>
Favorite Language:
<b><asp:Label runat="server"
style="color:blue" /></b><br />
<asp:Button runat="server" Text="Submit"/>
</form>
end example

Note

Avoid unnecessary data-binding. If the control has ViewState enabled, it needs to be data-bound only for initialization and then again when the underlying data source changes. However, if you disable ViewState for the control or for the page, you must call DataBind on every page load to re-populate the items.

Tip

Add dynamic items after data-binding. When adding items to a DropDownList control from both a data source and code in the page, be aware of the order in which they are added. The data-binding operation clears all the items that exist in the control and replaces them with the set from the data source. After DataBind is called, you can safely add items to the data-bound list. A good example of where this can prove valuable is when you want to add a default value of “Make a Selection” at the top of a drop-down list.




Microsoft ASP. NET Coding Strategies with the Microsoft ASP. NET Team
Microsoft ASP.NET Coding Strategies with the Microsoft ASP.NET Team (Pro-Developer)
ISBN: 073561900X
EAN: 2147483647
Year: 2005
Pages: 144

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net