OnDataBinding vs Inline: pros, cons and overhead

后端 未结 5 959
深忆病人
深忆病人 2020-12-09 20:08

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 W

5条回答
  •  时光取名叫无心
    2020-12-09 20:43

    I agree with caltrop. I like my markup to be clean and all my aspx/ascx code to reside in my code-behind files (where it belongs).

    I only have one thing to add. I prefer not to litter my code with OnDataBinding() events wired for each of my databound controls. Instead I do it all in the OnDataBinding() event of the User Control that is being embedded in the bindable-control (such as the repeater in your sample).

    For example, in my User Control's code-behind you would find:

    protected override void OnDataBinding(EventArgs e)
    {
        base.OnDataBinding(e);
    
        litExample.Text = Eval("ExampleField") + " - " + Eval("ExampleField2");
    }
    

    From here you can set the properties of all your controls or call other methods to set them. Notice how, in my example, I didn't need to perform the boxing like you did here: Literal lit = (Literal)(sender);

    That alone should save you on some performance (nanoseconds of course, but something worth measure). Read the section "Performance" here: http://msdn.microsoft.com/en-us/library/yz2be5wk%28v=vs.80%29.aspx

    I am also at war with using strings in my code. I would have either used const string variables to define "ExampleField" and "ExampleField2" or set them up as public properties in the User Control that could then be set by the containing control/page based on the column name of the data object it will be bound against. This affords more flexibility and re-use of the control.

    FYI: You don not need to call ToString() on Eval, as this method already returns a string.

提交回复
热议问题