How to call a method when binding a TextBox
I would like to bind () a textbox to an EditItemTemplate, but I need to pass the original value of the textbox to a function before displaying it. My goal is to format the value before displaying it. This is a complex formatting rule, so I cannot use any of the built-in formatters. It's easy to do when dealing with Eval (), but with Bind () it's a different story. I know it can be done using events in code, but I tried to do it all from the aspx page.
Example:
<EditItemTemplate>
<asp:TextBox ID="NameTextBox" Text=<%# Bind("Name") %> MaxLength="255" runat="server" />
</EditItemTemplate>
Thank...
source to share
Something like this should be very close to what you are looking for:
<asp:TextBox Id="TextBox1" runat="server" Text='<%# FormatValue(Eval("Name"), Container.DisplayItemIndex) %>' />
And in the code:
public object FormatValue(object value, int itemIndex)
{
var input = GridView1.Rows[itemIndex].FindControl("TextBox1") as TextBox;
if (input != null)
{
//do whatever you need with the old value
var oldValue = input.Text.Trim();
}
//format the value and send it back
return string.Format("My name is {0}", value);
}
source to share
You cannot do this from markup. ASP.NET has custom syntax code Bind
and generates custom code for it. Therefore, two way data binding does not support anything but Bind()
. You can find more information on this in How ASP.NET Data Binding Works with Eval () and Bind () Assertions of Eilon Lipton's article:
To the surprise of many readers, there is no binding method in ASP.NET! When ASP.NET parses your file and sees that you are using a data binding the expression (in the format angle-bracket-percentage-pound
"<%# %>"
) has special code to parse the syntaxBind
and generate some special code for it. When you use<%# Bind("Name") %>
it is not a real function call. If ASP.NET parses the code and finds theBind()
statement splits the statement into two parts. The first part is the one-way part of data binding, which ends with just a regularEval()
call. The second part is the reverse part, which is usually some code along the lines"string name = TextBox1.Text"
that takes the value back from where it was associated.The Non-Bind () binding operators are literal code (we use
CodeSnippetExpressions
inCodeDom
), so arbitrary code in the language of your choice. However, because ASP.NET must parseBind()
, two-way data binding does not support anything other thanBind()
. For example, the following syntax is invalid because it tries to call arbitrary code and be usedBind()
at the same time:<%# FormatNameHelper(Bind("Name")) %>
The only formats supported in two-way data binding areBind("field")
andBind("field", "format string {0}")
.
So, think about it in code, or use a method instead Eval
.
source to share