Load data into a UserControl as control properties or in control code behind?

我怕爱的太早我们不能终老 提交于 2019-12-24 17:04:44

问题


I'm building a UserControl that will repeat on the page a variable number of times. I'm trying to determine what the most efficient way to handle the data I will be loading into the Control. For the sake of simplicity, lets say it will be structured something like this:

<table>
    <tr>
        <td>Header Item</td>
    </tr>
    <tr>
        <td>Body Item n</td>
    </tr>
    <tr>
        <td>Body Item n+1</td>
    </tr>
    <tr>
        <td>Body Item n+2</td>
    </tr>
    <tr>
        <td>etc.</td>
    </tr>
    <tr>
        <td>Footer Item</td>
    </tr>
</table>

All of the data that will be loaded into this Control will come from a SQL Query. The Body items will be changing on every iteration of the control, but the Header and Footer items will be the same, and that is where I am trying to decide between a couple of options I can see.

  1. Build the query into the code behind of the control itself and repeat it for every iteration of the control, or:
  2. Query the data from the .aspx.cs page where the control will be used and deliver them as properties when the control is created.
  3. ?

Option 1 seems very inefficient. If we were talking about only two items, then I might just be inclined to accept the inefficiency, but we're talking about a lot more.

Option 2 seems plausible, but I have no idea if that is actually any better than option 1.

Thoughts? Other options?


回答1:


Use a Repeater control

Have a look here:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater(v=vs.80).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

<asp:Repeater runat="server">

 <HeaderTemplate>
  <table>
   <tr>
    <td>Header Item</td>
   </tr>
 </HeaderTemplate>

 <ItemTemplate>
  <tr>
   <td>Body Item <%# Eval("Number") %></td>
  </tr>
 </ItemTemplate>

 <FooterTemplate>
   <tr>
    <td>Footer Item</td>
   </tr>
  </table>
 </FooterTemplate>

</asp:Repeater>


来源:https://stackoverflow.com/questions/13986984/load-data-into-a-usercontrol-as-control-properties-or-in-control-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!