Thursday, January 24, 2008

Two way databinding in ASP.net

It is very easy to one-way databind from code behind to Markup:

<%@ Page CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<%# Name %>

namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
public string Name
{
get { return "JHA"; }
}

The other way from markup back to code-behind is a little difficult to write but Microsoft has created "Object Data Source" to make picking up data much easier:


<Form runat="server">
<asp:textbox runat="server" id="tb1">
<asp:objectdatasource runat="server" id="ods1" runat="server"
TypeName="WebApplication1._Default" SelectMethod="Test">
<SelectParameters>
<asp:ControlParameter ControlID="tb1" Name="Email" />
</SelectParameters>
</asp:objectdatasource>
<asp:Button runat="server" />
</Form>

In essence, Databinding become two-way using ObjectDataSource Select, update, Insert methods.


protected override void OnPreRender(EventArgs e)
{
DataBind();
ods1.Select();
}
public void Test(string Email) // email parameter will be filled by text from tb1
{
}

No comments: