Oak
Oak

Reputation: 1169

How to use a template in listview (asp.net, c#)

I have many pages that are showing same results in same layout (like search results, top viewed, recent added etc) If i want to change any field, i have to do this in all of the pages. Is it possible to have a template or usercontrol in listview where i can change this in one place and how to pass the id parameter?

Additional information: Now i have something like this:

<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource" DataKeyNames="id">
    <ItemTemplate>
                 Id:
         <asp:Label ID="IDLabel" runat="server" 
         Text='<%# Eval("id") %>' />
         Description:
         <asp:Label ID="DescriptionLabel" runat="server" 
              Text='<%# Eval("Description") %>' />
   </ItemTemplate>
</asp:ListView>

What i woild like to have is:

<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource" DataKeyNames="id">
    <ItemTemplate>
         <usrCtrl:info ID="info1" runat="server" /> 
   </ItemTemplate>
</asp:ListView>

and a file with template:

Id:
<asp:Label ID="IDLabel" runat="server" 
Text='<%# Eval("id") %>' />
Description:
<asp:Label ID="DescriptionLabel" runat="server" 
    Text='<%# Eval("Description") %>' />

Thanks, Jim Oak

Upvotes: 3

Views: 9502

Answers (2)

Kapil Khandelwal
Kapil Khandelwal

Reputation: 16144

Try this:

ListView:

<asp:ListView ID="ListView2" runat="server" 
    onitemdatabound="ListView2_ItemDataBound">
  <ItemTemplate>
     <usrCtrl:info Description_Lbl='<%# Bind("id") %>' 
                 ID_Lbl='<%# Bind("Description") %>' ID="info1"  runat="server" />
 </ItemTemplate>
</asp:ListView>

User Control Code:

info.ascx:

<%@ Control Language="C#" AutoEventWireup="true" 
                    CodeBehind="info.ascx.cs" Inherits="info" %>
<asp:Label ID="IDLabel" runat="server"  />
Description:
<asp:Label ID="DescriptionLabel" runat="server"  />

info.ascx.cs:

public partial class info: System.Web.UI.UserControl
{
    public string ID_Lbl {get;set;}
    public string Description_Lbl { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        IDLabel.Text = ID_Lbl;
        DescriptionLabel.Text = Description_Lbl;
    }
}

Upvotes: 2

Floremin
Floremin

Reputation: 4089

You can create a User Control (*.ascx file) with the entire ListView, and then expose DataSource to bind the data from your page.

I found this post helpful:

How to set DataSource property in.aspx file of a user control?

Upvotes: 1

Related Questions