Tutorial :Confused about databinding in ASP.NET


Lets say I have an object

class Person {      public string Name { get; set; }      public int Age { get; set; }  }  

And that object is retrieved from a Factory (ie Can't use SQLDataSource or anything like that)

Person person = PersonFactory.GetPerson();  

How can I two-way DataBind the two properties to Textboxes on a web form? I looked into FormView, but that doesn't seem to fit my needs as I am not iterating over a collection of objects. And when I tried to use it, I don't seem to be getting the posted values in the Person object in the FormUpdated event. And I am binding like this


<asp:Textbox Text=<%# Bind("Name") %> />  

Code behind

 FormView1.DataSource = new List() { person };   FormView1.DataBind();  

I feel like I am missing something really obvious. Should I be using a FormView? It doesn't seem like it a proper fit for simple data binding, but the <#% Bind %> method must be in some type of container -- is there a more suitable object?


You need to handle the updates to your FormView - the updates in the asp.net databound controls are not automatic. I'd also consider using an ObjectDataSource - keeping your binding all in the markup can make things easier to find. When you use the ObjectDataSource - it'll automatically wrap your single object in an IEnumerable, so binding to a method that returns a Person is acceptable. You could also consider using a DetailsView if you don't want to write out the form yoruself. In your case, you could do the following

<asp:FormView runat="server" DataSourceID="MyPersonDataSource"> ... </asp:FormView>  <asp:ObjectDataSource runat="server" ID="MyPersonDataSource"       TypeName="PersonFactory" DataObjectTypeName="Person"       SelectMethod="GetPerson" UpdateMethod="UpdatePerson" />  

And to facilitate this, you'd need an UpdateMethod(Person) method on your PersonFactory class. Doing it this way eliminates your binding from the codebehind, and will allow your updates to your person object to be persisted to your data store without you having to handle the update events yourself.


Try calling the DataBind method on your TextBox controls.

protected override void OnLoad(EventArgs e)  {       base.OnLoad(e);         MyTextBox1.DataBind();       MyTextBox2.DataBind();  }  

I've never tried doing two way binding in exactly this way before, but using the Bind("property") syntax, it should work this way as far as I know.

If calling the DataBind method doesn't work, then the FormView is your best bet.


DataBinder.Eval(Container.DataItem, "Name")  

This should do the trick, but I think you need some event-handling of your own to do the 2-way binding.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »