Question

I'm trying to display a row of data in a div rather than in a table if possible. So I want to control each of the td elements in a row, but without the table involved, so foreach row I'd put the elements inline and within a div so I can use them in some java script animation.

<asp:sqldatasource ID="dsEvents" runat="server" ConnectionString="<%$ ConnectionStrings:Maryville %>" runat="server" 
        SelectCommand="SELECT e.* FROM rew_Event e INNER JOIN rew_Timeframe t ON t.timeframeID = e.timeframeID WHERE e.dateStart >= @today AND e.active = 1 ORDER BY e.dateStart ASC">
        <SelectParameters>
            <asp:ControlParameter ControlID="hidDateTime" Type="DateTime" Name="today" />
        </SelectParameters>
</asp:sqldatasource>

So for this source I want to display each row into a div, and I don't want to deal with tables at all. Is this possible? I know that in PHP I would be able to query and then echo each data I selected anywhere on the page by creating a for or foreach loop. How can I do that same thing here?

Thanks!

Was it helpful?

Solution

Unfortunately, the SqlDataSource control is designed to work with data-bound controls via their DataSourceId attributes...Which is actually what makes it so easy to use! The SqlDataSource can be used with minimal code because its corresponding data is only retrieved when a data-bound control with a DataSourceId attribute equal to the SqlDataSource's ID exists during the page's pre-render life-cycle. You can read up on this a little more on the MSDN SqlDataSource Control Overview page.


Alternative methods and work-arounds

When I want to get reeeally inline with my server-side code (like for example placing field values within custom divs), I normally use one of the following techniques:

ONE: Create an ASP repeater control with custom ItemTemplates to return multiple rows of data.

This is probably the easiest method to implement; but since all references to the SQL data have to be made within the repeater control, it is somewhat limited in its usefulness. However, if you are looking to just get the job done for now, this is probably what you want to go with. Here are my bookmarked links regarding repeaters:


TWO: Reference server-side functions using inline server tags to return a single row of data or a scalar value.

IMHO, of all three methods, this one offers the best combination of server-side customization, simplicity, and server-client interaction. It quickly became my go-to method for displaying custom data. I'll construct an example. Let us assume I have an ASP.NET WebForms website that sells textbooks. In this website I have a page (view.aspx) that allows the student to view a textbook and contact the seller. In this page, I'll most likely want to display textbook info items such as Title, Author, and ISBN. The textbook information is stored in a SQL table or view called TextbookPostInfo. Each entry in this table is identified by its primary key postid. The postid value is passed to the page via a URL parameter.

I'll start by constructing a TextBookPost class to contain the info items...

Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient

Namespace MyClassLibrary
Public Class TextBookPost

            Sub New(ByVal post_id As Guid)

                Dim queryString As String = "select * from PostInfoView where postid = @postid"

                Using cmd As New SqlCommand(queryString, New SqlConnection(ConfigurationManager.ConnectionStrings("MyDbConnection").ConnectionString))
                    cmd.Parameters.AddWithValue("@postid", post_id).SqlDbType = SqlDbType.UniqueIdentifier

                    Dim rdr As SqlDataReader

                    Try
                        cmd.Connection.Open()
                        rdr = cmd.ExecuteReader
                        While rdr.Read
                            _postid = rdr("postid")
                            _author = rdr("author")
                            _isbn = rdr("isbn")
                            _title = rdr("title")
                        End While

                    Catch ex As Exception
                        'INSERT ERROR-HANDLING CODE'
                        cmd.Connection.Close()
                    End Try

                    cmd.Connection.Close()

                End Using

            End Sub

            Private _postid As Guid
            ''' <summary>
            ''' Gets the postid.
            ''' </summary>
            ''' <value></value>
            ''' <returns></returns>
            ''' <remarks></remarks>
            Public ReadOnly Property postid As Guid
                Get
                    Return _postid
                End Get
            End Property

            Private _title As String
            ''' <summary>
            ''' Gets the title of the textbook for this post.
            ''' </summary>
            ''' <value></value>
            ''' <returns></returns>
            ''' <remarks></remarks>
            Public ReadOnly Property title As String
                Get
                    Return _title
                End Get
            End Property

            Private _isbn As String
            ''' <summary>
            ''' Gets the isbn of the textbook for this post.
            ''' </summary>
            ''' <value></value>
            ''' <returns></returns>
            ''' <remarks></remarks>
            Public ReadOnly Property isbn As String
                Get
                    Return _isbn
                End Get
            End Property

            Private _author As String
            ''' <summary>
            ''' Gets the author of the textbook for this post.
            ''' </summary>
            ''' <value></value>
            ''' <returns></returns>
            ''' <remarks></remarks>
            Public ReadOnly Property author As String
                Get
                    Return _author
                End Get
            End Property
End Class
End Namespace

Now that I've got a pretty little container for my info items, let's add some code in the page_load to retrieve this information using the given URL parameter postid.

View.aspx.vb (my code-behind file)...

Imports System.Data.SqlClient
Imports System.Data
Imports MyClassLibrary
Partial Class view
    Inherits System.Web.UI.Page

Private _thispost As TextBookPost = Nothing

    ''' <summary>
    ''' Gets the information for the current post.
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property thispost As TextBookPost
        Get
            Return _thispost
        End Get
    End Property

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            If Request.QueryString("postid") Is Nothing Then GoTo NoPostId
            Dim postid As Guid = Guid.Parse(Request.QueryString("postid").ToString)

            Dim tb As New TextBookPost(postid)
            _thispost = tb
        End If

        Exit Sub
NoPostId:
            'INSERT CODE TO HANDLE INVALID POST ID'
    End Sub

So now I have a nice and neat textbookpost object stored as a variable in my code-behind. This variable can now be accessed by myself or (if you are managing a team-development project) your font-end engineer/developer when creating the page's markup.

View.aspx

<HTML>
    <Body>
    <form id="form1" runat="server">
    <div class="post-info-container">
        <!-- ========================================= -->
        <!-- Title -->
        <!-- ========================================= -->
        <div class="post-info-item-title post-info-item">
            <span class="post-info-item-label-title post-info-item-label item-label">
                Title
            </span>
            <span class="post-info-item-text-title post-info-item-text item-text">
                <asp:Label runat="server" ID="titlelabel">
                    <%= thispost.title%>
                </asp:Label>
            </span>
        </div>

        <!-- ========================================= -->
        <!-- Author -->
        <!-- ========================================= -->
        <div class="post-info-item-author post-info-item">
            <span class="post-info-item-label-author post-info-item-label item-label">
                Author
            </span>
            <span class="post-info-item-text-author post-info-item-text item-text">
                <asp:Label runat="server" ID="authorlabel">
                    <%= thispost.author%>
                </asp:Label>
            </span>
        </div>
        <!-- ========================================= -->
        <!-- ISBN -->
        <!-- ========================================= -->
        <div class="post-info-item-isbn post-info-item">
            <span class="post-info-item-label-isbn post-info-item-label item-label">
                ISBN
            </span>
            <span class="post-info-item-text-isbn post-info-item-text item-text">
                <asp:Label runat="server" ID="isbnlabel">
                    <%= thispost.isbn%>
                </asp:Label>
            </span>
        </div>
    </div> 
    </form>
    </Body>
</HTML>

THREE: Construct a Web API and retrieve the data using jQuery $.Get() or $.ajax call.

This method is works extremely well when you want to perform partial-page updates the correct way (i.e., without using update-panels). FYI: If you are still using update panels, pay attention to this section. Implementing MVC is a little more complex than our previous example and probably beyond the scope of this answer, so instead here are some very useful links which I had bookmarked:

That last link explains how to perform a post action (as opposed to a get action), but it contains a lot of code examples and discussion on how to make it work. The method overall is great for customization since you can manipulate the data freely with javascript, but it has a couple drawbacks that deserve mentioning:

  • Increased exposure to security vulnerabilities including cross-site forgery requests.
  • Passing multiple parameters can be tricky when posting data (see the last link).
  • Probably some other issues I can't remember at this time...

Conclusion

All three methods are important, but they're situational. You'll just have to decide which method is best for your goal. Another useful technique is creating ASP.NET custom server controls, but this is a little more complex and normally involves creating a separate Visual Studio project. Anyhow...I hope this helps.

OTHER TIPS

You could use a Repeater, something like this:

<asp:Repeater ID="test" runat="server">
<HeaderTemplate>
   <div class="rowcontainer">
</HeaderTemplate>
<ItemTemplate>
   <div style="float:left;">
      <%#Eval("Column1") %>
   </div>
</ItemTemplate>
<FooterTemplate>
   </div>
</FooterTemplate>
</asp:Repeater>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top