Saturday, January 05, 2008

A User Interface Data Binding Overview in asp.net

Granularity (one field, one control) :

A definition of databing could be having a link between the field in the datasource and a control.

When we talk about data binding, the first thing that should come to mind, is that we are binding fields to controls. In more detail, when we use a GridView to bind it to a table, in fact we are binding each field in the database to a specific control, present in the form of a collection, which makes us say, we are binding a table to the grid, while the granular aspect of it is that we are binding many fields to many controls.

Binding Scripting Syntax for Grids, Datalists, Formviews and detailviews:

Two way binding (very popular)

<%
   1: # Bind("fieldname") 
%>



One way Binding (ReadOnly)




<%
   1: # Eval("fieldname") 
%>


Another one is :


<%
   1: # DataBinder.Eval(Container.DataItem, "fieldname") 
%>



 



This are helper Functions. Here's how they work :



when we have a textbox inside a TemplateField, in a Gridview : We have the following Syntax :




<TemplateField>
<EditItemTemplate>
<asp:TextBox id="txtName" runat="server" Text='<%# Bind("Name") %>' />
</EditItemTemplate>
</TemplateField>



In fact, The Bind Method is executed during the ItemDataBound Event (one popular event in the 1.1 DataGrid control used to initilize child controls in a GridView). The Bind method helps not having to write code behind syntax to bind each field during insert and update.


 


Best Practices using the SqlDataSource Control :


If we notice, using SQLDataSource, (note : thanks Adnane for the tip), there's a property named DataSourceMode :


This property is really great, since it gives us DataSet Mode and DataReader Mode. DataSet Mode is set by default, nice, that way The paging and sorting can work by default.


 


image


 


When to change the DataSourceMode property:


For better use, there' no need in using the default mode to fill a DropDownList or a ListBox, instead we choose DataReader Mode, which will be of course more efficient.


 


For differences between DataReader and DataSet, please take a look at a previous post (DataSet vs DataReader). this post includes links to msdn explaining the difference, as well as giving a breif overview of the difference.


 


Comments are welcome

No comments: