I thought I would ask this question to see why many examples and people prefer to use inline databinding in the aspx code vs implementing an OnDataBinding event when using WebForms.
For any databound control (eg. Repeater, GridView, etc) I always implement the OnDataBinding method for field level controls if I need to do anything that isn't built in out of the box (eg. I need to do an Eval). Most examples I see have the code right in the aspx page using the inline <%# syntax.
Example of inline ASP.NET code:
<asp:Literal ID="litExample" runat="server"
Text='<%# Eval("ExampleField").ToString() %>' />
Example of how I prefer to do it:
In the aspx:
<asp:Literal ID="litExample" runat="server"
OnDataBinding="litExample_DataBinding" />
In the codebehind .cs:
protected void litExample_DataBinding(object sender, System.EventArgs e)
{
Literal lit = (Literal)(sender);
lit.Text = string.Format("{1} - {2}",
Eval("ExampleField").ToString(),
Eval("ExampleField2").ToString());
}
I personally prefer the codebehind method because it keeps my aspx pages clean and I don't have all this inline code all over the place and the next guy just knows to always look in the .cs files for code changes. The seperation of presentation and code is also maintained better this way as the HTML is place holders only and the codebind is determining what is actually being put in control.
Now these are very basic examples. The field could be a integer that you want to format with leading 0s or a DateTime that needs a specific format etc. It could also take all sort of manipulation and code to get the finally value that should be stored in the 'Text' property at the end.
Where do you draw the line and move it to the codebehind if you are using inline code?
What are the pros and cons for doing it either way?
Does one take more overhead than the other?
Edit Note: I am not talking about assigning a value to a control that is just on the page but one that is being databound to because it exists in a repeater template or gridview item template etc... Obviously a literal sitting on a page you can just assign in code.
Edit Note: I thought I would gather more response, especially with regards to the overhead. Do most people NOT use the OnDataBinding events?
I much prefer the opposite. I prefer to keep my code-behind limited to procedural code, and keep all my declarative code in my Aspx page. In your example above, the literal is absolutely declarative and therefore (by my preference) would not belong in code-behind. Much more robust functionality generally goes in my code-behind, and I don't want my developers to be cluttered by having to sift through a bunch of initialization lines when trying to understand it.