Reputation: 13308
What's the difference between these code samples? Which approach is right?
<asp:Label ID="lblShorName" runat="server" Text="<%#Customer.ShorName%>" />
lblShorName.DataBind();
and
lblShorName.Text = Customer.ShorName;
Upvotes: 0
Views: 100
Reputation: 218827
There isn't much of a difference that I know of (though I'll be interested in other people's answers to correct me if I'm wrong on that). It's just a matter of coding style and preference.
Personally, I prefer the latter. I feel that it's cleaner and separates the markup from the functionality which drives the markup. But that's just me.
(I also tend to prefer not using data binding where I don't feel I need to. But, again, it's a preference of how you want to use the tooling that's provided. For example, in an ASP.NET MVC view I'm more likely to write a loop and output HTML within that loop than I am to use any kind of repeater or grid control and bind data to it. Just personal preference.)
A lot of it also comes down to where in your application you want to perform these actions. The former example keeps it on the page, whereas the latter example can be wrapped in conditionals, re-factored into another method, etc. If it's possible that the value in question isn't always going to come from Customer.ShortName
then I'd go with the latter example to add that additional logic around it.
Upvotes: 2
Reputation: 508
The approach depends when you want to set the label. lblShorName.Text = Customer.ShorName;
Can be used in different methods, events, timers. If you want to set it only at the beginning you can use the first one.
Upvotes: 1
Reputation: 5266
Not much really, when you use databinding your value is set at the time of databinding, however if you set it in the code-behind you can set it any stage of the pages lifecycle.
You may have some logic behind the value too and this is more readable/maintainable in the code-behind.
Upvotes: 0