I am trying to implement the simplest possible (so it seemed to me) databinding of a TextBox to a property of the page, except the databinding is supposed to be two-way, so instead of <%# Test %>, I use <%# Bind("Test") %>. (Actually, the goal is to have a single object as a property and to bind to its properties, but let's start from something simple.) I am testing it on this simple code:
TestForm.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TestTextBox" runat="server" Text='<%# Bind("Test") %>' />
</div>
</form>
</body>
</html>
TestForm.aspx.cs:
using System;
namespace WebApplication1
{
public partial class TestForm : System.Web.UI.Page
{
public string Test { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Test = "Hello";
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
DataBind();
}
}
}
The call of DataBind() results in an InvalidOperationException: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
What is wrong with this approach?