开发者

Binding Data From SQL Server to a Label(s)

I'm doing such a small web page that contain 4 main HTML div which should contain last 4 NEWS from a SQL Database.

so I've designed them, and put in each on a label control, and an Image control.

and to bind information from the SQL to them, I've used (DataView) object, and using a loop from 0 to 3 I've get the data I need.

but I believe that way is not the perfect one! so I need something more clear and effec开发者_StackOverflowtiveness!


create an <asp:repeater ... /> control on your page and bind it to your SQL data source.
Create the appropriate Select statement within your data source (or use LINQ, or whatever you like).

layout the repeater control something like this

        <asp:Repeater ID="Repeater1" runat="server" DataSourceID="MyDataSource">
            <HeaderTemplate>
                <div style="height: 30px;">
                     Header info
                </div>
            </HeaderTemplate>
            <ItemTemplate>
               <div>
                  <%# Eval("SomeInfo")%>
                  <img src='<%# Eval("SomeImage")%>' title='<%# Eval("SomeImageTitle")%>' alt='<%# Eval("SomeImageAlt")%>' />
               </div>
            </ItemTemplate>
            <SeparatorTemplate>
                <hr />
            </SeparatorTemplate>
            <FooterTemplate>
                <div style="height: 25px;">
                       Footer Stuff
                </div>
            </FooterTemplate>
        </asp:Repeater>


Don't know what version of .NET you are using, so that may affect this answer, but...

LinqDataSource would be a nice way of doing this, as you can specify data-level filtering (i.e. TOP 3), instead of page-level filtering (in memory looping).


Assuming that your data view contains only the 4 items you want to display, you probably want to make use of one of the DataRepeater style ASP.NET controls.

You bind the DataView to the controls Datasource property, and call .DataBind() for the page or the control (the page call is recursive over all controls)

Inside the DataRepeater will be a "Template" control, the content of which would be something like

<div style="st1"><%# Eval("NewsText") %>&nbsp;<img src='<%# Eval("ImgSrc") %>' /></div>


You could retrieve data using LINQ.

To exemplify:

var latestNews = (from n in db.News orderby n.Date descending select n).Take(4).ToList();

label1.Text = latestNews[0].Content;
label2.Text = latestNews[1].Content;
label3.Text = latestNews[2].Content;
label4.Text = latestNews[3].Content;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜