The following is the basic syntax to declare a ListView Web
Server Control in an ASPX page.
Listing 1: ListView definition
<asp:ListView ID="ListView1" runat="server">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</LayoutTemplate>
</asp:ListView>
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "ColumnName")%>
</ItemTemplate>
The layout template specifies the basic structure of a
ListView control. A Placeholder control must be declared to use the ListView
control. For example, if you want to display a report title then you could have
a table row just above the Placeholder. And, if you want to display report
footer, then you could have a table row just below the Placeholder. This has
been explained later in this article, where we add rows to a ListView.
There are many ways we could bind the ListView object. In
the following example, the ListView is being populated using a Stored
Procedure. The DataItem "ColumnName" is one of the columns which are
being returned by the Stored Procedure. During the Page_Load event, the Stored
Procedure is executed and bind to the ListView.
Listing 2: Binding a ListView Web Server Control
protected void PopulateListView()
{
SqlConnection myConn = CreateConnection();
// CreateConnetion is a custom method which returns SQL connection.
SqlCommand myCmd = new SqlCommand("pubs_get_authors", myConn);
myCmd.CommandType = CommandType.StoredProcedure;
try
{
myConn.Open();
ListView1.DataSource = myCmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (SqlException se)
{
lblMsg.Text = se.Message;
}
catch (Exception e)
{
lblMsg.Text = e.Message;
}
finally{}
ListView1.DataBind();
myConn.Close();
}
In the above code listing, the stored proc
“pubs_get_authors” is invoked. Try … Catch … Finally has been used to trap any
unexpected errors that might occur during the database operation. The definition
of CreateConnection method is included in the code sample at the end of this
article.
Figure 1: ListView control Output
