SOFTWARE DEVELOPMENT

Creative Tailor Made - Bespoke - Custom Software Solutions

Bind ListView to DataTable

This is a very basic example to show that binding ListView is really easy.

For this tutorial i created a new table named Members with the following fields:

database example

In the first example we use SqlDataSource object to retrieve the records from the table Members:

ASP.NET:

    <asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1">
    <LayoutTemplate>
    <table runat=" server" id=" table1">
    <tr runat=" server" id=" groupPlaceholder"></tr>
    </table>
    </LayoutTemplate>
    <GroupTemplate>
    <tr runat=" server" id=" tableRow">
    <td runat=" server" ID=" itemPlaceholder" />
    </tr>
    </GroupTemplate>
    <ItemTemplate>
    <td id="td1" runat="server">
    <asp:Label ID="lblFirstName" runat="server" Text='<%# Eval("FirstName") %>'></asp:Label>
    <asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName") %>'></asp:Label>
    <asp:Label ID="lblNickName" runat="server" Text='<%# "(aka " & Eval("NickName") & ")" %>'></asp:Label>
    <asp:Label ID="lblFavoriteLanguage" runat="server" Text='<%# " - Favorite Language: " & Eval("FavoriteLanguage") %>'></asp:Label>
    </td>
    </ItemTemplate>
    </asp:ListView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    SelectCommand="SELECT [FirstName], [LastName], [NickName], [FavoriteLanguage] FROM [Members]">
    </asp:SqlDataSource>

As you can see using SqlDataSource object is very neat and simple!
If you want to go further let’s see how to fetch the same data without DataSource object.

For that i am going to create Stored Procedure and name it GetMembers:

T-SQL:

    CREATE PROCEDURE GetMembers

    AS
    SET NOCOUNT ON
    SELECT
        FirstName,
        LastName,
        NickName,
        FavoriteLanguage
    FROM
        Members

Then i will write a small function of DataTable datatype:

VB.NET

Private Function GetMembers() As DataTable
    Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
    Dim command As SqlCommand = connection.CreateCommand
    command.CommandText = "GetMembers"
    command.CommandType = Data.CommandType.StoredProcedure
 
    Dim table As New DataTable
    connection.Open()
    table.Load(command.ExecuteReader(Data.CommandBehavior.CloseConnection))
 
    Return table
End Function

Now i just use this function as DataSource for my ListView. Just put this in the load event handler:

VB.NET

Protected Sub Page_Load(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles Me.Load
    Me.ListView1.DataSource = GetMembers()
    Me.ListView1.DataBind()
End Sub

Well that’s it. Sorry if you expected more.