ASP.NET WebForms Nested Repeater With LINQ Group Data Source - c#

I have a LINQ grouping that I'd like to use to populate parent and child repeater controls.
<asp:Repeater ID="Parent" runat="server" OnItemDataBound="Parent_ItemDataBound">
<ItemTemplate>
<%# Eval("Key") %>
<asp:Repeater ID="Child" runat="server">
<ItemTemplate>
<%# Eval("Id") %>
<%# Eval("Name") %>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
public class Dog
{
public int Id { get; set; }
public string Name { get; set; }
public string Breed { get; set; }
}
private IEnumerable<IGrouping<string, Dog>> GetDogs()
{
var dogs = new List<Dog>
{
new Dog
{
Id = 1,
Name = "Rex",
Breed = "Poodle",
},
new Dog
{
Id = 2,
Name = "Fido",
Breed = "Terrier",
},
new Dog
{
Id = 3,
Name = "Killer",
Breed = "Pit Bull",
}
};
return dogs.GroupBy(_ => _.Breed);
}
protected void Page_Load(object sender, EventArgs e)
{
Parent.DataSource = GetDogs();
Parent.DataBind();
}
protected void Parent_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var item = e.Item;
if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem))
{
var repeater = (Repeater)item.FindControl("Child");
// I'm stuck on this code...
//repeater.DataSource = what to do?
//repeater.DataBind();
}
}
I'm trying to set the child repeater's data source in the Parent_ItemDataBound event. How do I do this? item.DataItem is type object and I can't figure out how to obtain the list of dogs that's inside the data item.

Expanding on Joshua's correct answer. If the 4.5 runtime is available to you, you can declare the types on the repeater itself so you will not have to bind the ItemDataBound event.
<ul>
<asp:Repeater runat="server" ID="Parent" ItemType="IGrouping<String, Dog>">
<ItemTemplate>
<li><%# Item.Key %><ul>
<asp:Repeater runat="server" ID="Child" ItemType="Dog" DataSource="<%#Item%>">
<ItemTemplate>
<li><%# Item.Id %></li>
<li><%# Item.Name %></li>
</ItemTemplate>
</asp:Repeater>
</ul></li>
</ItemTemplate>
</asp:Repeater>
</ul>

You can get the data from e.Item.DataItem. You should be able to cast this to IGrouping. Then you can get the inner repeater by looking for the control in the current repeaters repeateritem. Then bind the data from DataItem to the nested repeater.
This code below should work.
All this assumes you don't wrap the nested repeater in other controls.
protected void Parent_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var item = e.Item.DataItem as IGrouping<string, Dog>;
if (item == null)
return;
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
var repeater = e.Item.FindControl("Child") as Repeater;
if (repeater != null)
{
repeater.DataSource = item;
repeater.DataBind();
}
}
}

Related

Get Updated Value of a UserControl TextBox within a ListView

I have a page SendResults.aspx that holds a button and a ListView with ItemTemplate set to a user control (3 labels and 2 textboxes) that gets it's data from a matching object.
On Page_Load I fill the List with data (this works well).
When the button is clicked I want to take the user input in the user-control's textboxes and do something with it.
However I always get the initial value and not the updated one.
Here is the code:
The user-control "MatchControl.ascx"
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MatchControl.ascx.cs" Inherits="TotoMondeal.Controls.MatchControl" %>
<div>
<asp:Image ID="Team1FlagImage" runat="server" />
<asp:Label ID="Team1Label" runat="server" Width="150px"></asp:Label>
<asp:TextBox ID="Team1TextBox" runat="server" MaxLength="2" TextMode="Number" Width="50px" AutoPostBack="true" OnTextChanged="Team1TextBox_TextChanged"></asp:TextBox>
<asp:Label ID="Colon" runat="server" Font-Size="XX-Large" Text=":"></asp:Label>
<asp:TextBox ID="Team2TextBox" runat="server" MaxLength="2" TextMode="Number" Width="50px"></asp:TextBox>
<asp:Label ID="Team2Label" runat="server" Width="150px"></asp:Label>
<asp:Image ID="Team2FlagImage" runat="server" />
</div>
The user-control code-behind:
public partial class MatchControl : System.Web.UI.UserControl
{
public Match Match
{
get
{
object obj = ViewState["Match"];
return (obj == null) ? new Match() : (Match)obj;
}
set
{
ViewState["Match"] = value;
}
}
public string Team1Score
{
get { return Team1TextBox.Text; }
set { Team1TextBox.Text = value; }
}
public string Team2Score
{
get { return Team2TextBox.Text; }
set { Team2TextBox.Text = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
Team1Label.Text = Match.Team1Name;
Team2Label.Text = Match.Team2Name;
Team1TextBox.Text = Match.Team1Score.ToString();
Team2TextBox.Text = Match.Team2Score.ToString();
Team1TextBox.Enabled = Match.EnableTextBox;
Team2TextBox.Enabled = Match.EnableTextBox;
Team1FlagImage.ImageUrl = #"~/FlagImages/" +Match.Team1Name + ".png";
Team2FlagImage.ImageUrl = #"~/FlagImages/" + Match.Team2Name + ".png";
}
protected void Team1TextBox_TextChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
{
try
{
Match updatedMatch = new Match()
{
MatchId = Match.MatchId,
MatchDate = Match.MatchDate,
Result = Match.Result,
Team1Name = Match.Team1Name,
Team1Score = Convert.ToInt32(textBox.Text),
Team2Name = Match.Team2Name,
Team2Score = Match.Team2Score,
EnableTextBox = Match.EnableTextBox
};
Match = updatedMatch;
}
catch (Exception ex)
{
throw ex;
}
}
}
The SendResults.aspx:
<%# Page Title="שלח תוצאות" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="SendResults.aspx.cs" Inherits="TotoMondeal.SendResults" %>
<%# Register TagPrefix="TOTO" TagName="MatchControl" Src="~/Controls/MatchControl.ascx" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %>.</h2>
<div class="jumbotron">
<asp:ListView ID="TodayMatchesList" runat="server">
<ItemTemplate>
<TOTO:MatchControl ID="MatchControl" Match="<%# Container.DataItem %>" runat="server" />
</ItemTemplate>
</asp:ListView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</asp:Content>
the SendResults code-behind:
public partial class SendResults : Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Match> matches = new List<Match>();
matches = Queries.GetTodayMatches(DateTime.Now);
foreach (Match match in matches)
{
match.EnableTextBox = true;
}
this.TodayMatchesList.DataSource = matches;
this.TodayMatchesList.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < TodayMatchesList.Items.Count; i++)
{
MatchControl match = (MatchControl)TodayMatchesList.Items[i].FindControl("MatchControl");
TextBox textBox = (TextBox)match.FindControl("Team1TextBox");
string txt = textBox.Text;
}
}
}
The problem is that in this line:
TextBox textBox = (TextBox)match.FindControl("Team1TextBox");
string txt = textBox.Text;
I always get the initial value from the database, and not the user updated input.
Please help I'm new at this.
Your List is getting overwritten every time you post back. Add this in Page_Load for SendResults
if ( !Page.IsPostBack )
{
List<Match> matches = new List<Match>();
matches = Queries.GetTodayMatches(DateTime.Now);
...etc...
}
In addition to checking IsPostBack you need to handle saving your control properties in the ViewState. As suggested here: User control (ascx) and properties
Example from post:
public string Title {
get { return Convert.ToString(ViewState["Title"]); }
set { ViewState["Title"] = value; }
}
You would do this in your control class.

Insert <p> tags with C#?

This is sort of a weird question, but is there a way to insert <p> tags around some imported text? I have a list of blog entries, each of which comes from its own source (I think it's a copy-paste job into Sitecore). All entries have an "Introduction" which is the blurb about the article. Some of these has <p> tags enclosing them and others do not (I'm not sure why and I can't change the source material--I can only have control on how it looks when it comes into the blog listing page) I'm thinking there should be a check to see if they do exist first, although I am not sure how that could be done.
This is the front end for the blog listing:
<asp:GridView ID="EntryList" runat="server" OnItemDataBound="EntryDataBound" AllowPaging="true" PageSize="3" AutoGenerateColumns="false" EnablePersistedSelection="true" DataKeyNames="EntryID" OnPageIndexChanging="grdTrades_PageIndexChanging" GridLines="None" PagerSettings-Position="TopAndBottom" CssClass="mGrid" pagerstyle-cssclass="pagination" rowstyle-cssclass="norm" alternatingrowstyle-cssclass="altColor" width="100%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<li class="wb-entry-list-entry" >
<div class="imgOuter">
<div class="imgInner">
<asp:Image runat="server" ID="EntryImage" CssClass="wb-image" ImageUrl='<%# Eval("Image") %>' />
</div>
</div>
<div class="outer">
<div class="wb-entry-detail" >
<h2>
<%# Eval("Title") %>
</h2>
<div class="wb-details">
<%# Eval("EntryDate") %>
<%# Eval("Author") %><br />
<%# Eval("AuthorTitle") %>
</div>
<%# Eval("Introduction") %>
<asp:HyperLink ID="BlogPostLink" runat="server" CssClass="wb-read-more" NavigateUrl='<%# Eval("EntryPath") %>'><%# Sitecore.Globalization.Translate.Text("READ_MORE")%></asp:HyperLink>
<asp:PlaceHolder ID="CommentArea" runat="server">
<span class="wb-comment-count">
</span>
</asp:PlaceHolder>
</div>
</div>
</li>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<%#Sitecore.Globalization.Translate.Text("NO_POSTS_FOUND")%>
</EmptyDataTemplate>
And this is the codebehind:
Database db = Sitecore.Context.Database;
protected const string DEFAULT_POST_TEMPLATE = "/layouts/WeBlog/PostListEntry.ascx";
protected Size m_imageMaxSize = Size.Empty;
protected void grdTrades_PageIndexChanging(Object sender, GridViewPageEventArgs e)
{
EntryList.PageIndex = e.NewPageIndex;
string tag = Request.QueryString["tag"];
BindEntries(tag);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string requestedToShowStr = Request.QueryString["count"] ?? "0";
int requestedToShow = 0;
int.TryParse(requestedToShowStr, out requestedToShow);
string startIndexStr = Request.QueryString["startIndex"] ?? "0";
int startIndex = 0;
int.TryParse(startIndexStr, out startIndex);
string tag = Request.QueryString["tag"];
Item CurrentItem = Sitecore.Context.Item;
BindEntries(tag);
string blogUrl = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item);
}
}
protected void BindEntries(string tag)
{
DataSet ds = new DataSet();
DataTable ResultTable = ds.Tables.Add("EntryTable");
ResultTable.Columns.Add("EntryID", Type.GetType("System.String"));
ResultTable.Columns.Add("EntryPath", Type.GetType("System.String"));
ResultTable.Columns.Add("Title", Type.GetType("System.String"));
ResultTable.Columns.Add("EntryDate", Type.GetType("System.String"));
ResultTable.Columns.Add("Author", Type.GetType("System.String"));
ResultTable.Columns.Add("AuthorTitle", Type.GetType("System.String"));
ResultTable.Columns.Add("Introduction", Type.GetType("System.String"));
ResultTable.Columns.Add("Image", Type.GetType("System.String"));
Item CurrentItem = Sitecore.Context.Item;
Item BlogStart = ScHelper.FindAncestor(CurrentItem, "BlogHome");
Item[] EntryArray = null;
if (tag == "")
EntryArray = BlogStart.Axes.SelectItems(#"child::*[##templatename='Folder']/*[##templatename='Folder']/*[(##templatename='BlogEntry' ) ]");
else
EntryArray = BlogStart.Axes.SelectItems(#"child::*[##templatename='Folder']/*[##templatename='Folder']/*[(##templatename='BlogEntry' and contains(#tags,'" + tag + "' )) ]");
ArrayList PostList = new ArrayList();
if (EntryArray != null)
{
foreach (Item EntryItem in EntryArray)
{
if (EntryItem.Fields["Post Date"].Value != "")
{
BlogEntryProcessor.BlogEntrys obj1 = new BlogEntryProcessor.BlogEntrys();
obj1.Description = EntryItem.Fields["Introduction"].Value;
obj1.Guid = EntryItem.ID.ToString();
obj1.Link = ScHelper.GetPath(EntryItem);
obj1.PostDate = formatDateCmp(EntryItem.Fields["Post Date"].Value);
obj1.Title = EntryItem.Fields["Title"].Value;
PostList.Add(obj1);
}
}
PostList.Sort();
PostList.Reverse();
foreach (BlogEntryProcessor.BlogEntrys obj in PostList)
{
DataRow dr = ResultTable.NewRow();
Item BlogEntry = db.Items[obj.Guid];
dr["EntryID"] = obj.Guid;
dr["EntryPath"] = ScHelper.GetPath(BlogEntry);
dr["Title"] = BlogEntry.Fields["Title"].Value;
dr["EntryDate"] = GetPublishDate(BlogEntry);
dr["Author"] = GetAuthor(BlogEntry);
dr["AuthorTitle"] = GetAuthorTitle(BlogEntry);
dr["Introduction"] = BlogEntry.Fields["Introduction"].Value;
//TODO: get Default Image
string EntryThumbImage = BlogEntry.Fields["Thumbnail Image"].Value;
string EntryImage = BlogEntry.Fields["Image"].Value;
string ArtImage = "http://fpoimg.com/140x140";
if (EntryImage != "")
{
Sitecore.Data.Fields.XmlField fileField = BlogEntry.Fields["Image"];
ArtImage = "/" + ScHelper.GetCorrectFilePath(fileField);
}
else if (EntryThumbImage != "")
{
Sitecore.Data.Fields.XmlField fileField = BlogEntry.Fields["Thumbnail Image"];
ArtImage = "/" + ScHelper.GetCorrectFilePath(fileField);
}
dr["Image"] = ArtImage;
ResultTable.Rows.Add(dr);
}
EntryList.DataSource = ds;
EntryList.DataMember = "EntryTable";
EntryList.DataBind();
}
}
protected string GetAuthorTitle(Item entry)
{
string OutName = "";
string AuthorID = entry.Fields["Author"].Value;
Item AuthorItem = db.Items[AuthorID];
if (AuthorItem != null)
OutName = AuthorItem.Fields["Author Title"].Value;
return OutName;
}
protected string GetAuthor(Item entry)
{
string OutName = "";
string AuthorID = entry.Fields["Author"].Value;
Item AuthorItem = db.Items[AuthorID];
if (AuthorItem != null)
OutName = string.Format("<br />By <a href='{0}'>{1}</a>", ScHelper.GetPath(AuthorItem), AuthorItem.Fields["Author Name"].Value);
return OutName;
}
protected string GetPublishDate(EntryItem CurrentEntry)
{
string pDate = GOJOHelper.FormatDate(((Item)CurrentEntry).Fields["Post Date"].Value);
return pDate;
}
protected void EntryDataBound(object sender, ListViewItemEventArgs args)
{
if (args.Item.ItemType == ListViewItemType.DataItem)
{
var dataItem = args.Item as ListViewDataItem;
var control = dataItem.FindControl("EntryImage");
if (control != null)
{
var imageControl = control as global::Sitecore.Web.UI.WebControls.Image;
imageControl.MaxWidth = m_imageMaxSize.Width;
imageControl.MaxHeight = m_imageMaxSize.Height;
var entry = dataItem.DataItem as EntryItem;
if (entry.ThumbnailImage.MediaItem == null)
imageControl.Field = "Image";
}
}
}
//string to use to sort the dates - must have 2 digit for month and day
private string formatDateCmp(string date)
{
// Set the dateResult for the TryParse
DateTime dateResult = new DateTime();
// Split the date up. ie. 20090101T000000
string[] TempStr = date.Split('T');
// Set the date to the characters before the T
date = TempStr[0];
// Insert a slash after the first 4 characters and after 7
date = date.Insert(4, "/").Insert(7, "/");
return date;
}
You can always do something like...
dr["Introduction"] = BlogEntry.Fields["Introduction"].Value
.Replace("\n\n", "</p><p>");
... or whichever escape characters are being used to denote separation of paragraphs in your source data. Alternatively, you could use Regex utilities. See Example 3 in this article for further reference.
Firstly in your GridView you've got
OnItemDataBound="EntryDataBound"
OnItemDataBound isn't an event of GridView I'm a little surprised that works!
Use
OnRowDataBound="EntryList_RowDataBound"
This is my common pattern for GridView's and Repeaters, noticed I've used a Literal control in the HTML, I'm not a mega fan of Eval! Also note that if (dataItem == null) just if there's a data item for that row, RowTypes like header and footer don't have any data, it's easier than the typical if(e.Row.RowType == DataControlRowType.Header) etc
<asp:GridView ID="EntryList" runat="server" OnRowDataBound="EntryList_RowDataBound" AllowPaging="true" PageSize="3" AutoGenerateColumns="false" EnablePersistedSelection="true" DataKeyNames="EntryID" OnPageIndexChanging="grdTrades_PageIndexChanging" GridLines="None" PagerSettings-Position="TopAndBottom" CssClass="mGrid" PagerStyle-CssClass="pagination" RowStyle-CssClass="norm" AlternatingRowStyle-CssClass="altColor" Width="100%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<li class="wb-entry-list-entry">
<div class="imgOuter">
<div class="imgInner">
<asp:Image runat="server" ID="EntryImage" CssClass="wb-image" ImageUrl='<%# Eval("Image") %>' />
</div>
</div>
<div class="outer">
<div class="wb-entry-detail">
<h2>
<%# Eval("Title") %>
</h2>
<div class="wb-details">
<%# Eval("EntryDate") %>
<%# Eval("Author") %><br />
<%# Eval("AuthorTitle") %>
</div>
<asp:Literal runat="server" ID="IntroductionLiteral"/>
<asp:HyperLink ID="BlogPostLink" runat="server" CssClass="wb-read-more" NavigateUrl='<%# Eval("EntryPath") %>'><%# Sitecore.Globalization.Translate.Text("READ_MORE")%></asp:HyperLink>
<asp:PlaceHolder ID="CommentArea" runat="server">
<span class="wb-comment-count"></span>
</asp:PlaceHolder>
</div>
</div>
</li>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<%#Sitecore.Globalization.Translate.Text("NO_POSTS_FOUND")%>
</EmptyDataTemplate>
</asp:GridView>
.cs file
protected void EntryList_RowDataBound(object sender, GridViewRowEventArgs e)
{
var dataItem = e.Row.DataItem as EntryItem;
if (dataItem == null)
return;
var imageControl = e.Row.FindControl("EntryImage") as global::Sitecore.Web.UI.WebControls.Image;
var introductionControl = e.Row.FindControl("IntroductionLiteral") as Literal;
if (imageControl == null || introduction == null)
return;
imageControl.MaxWidth = m_imageMaxSize.Width;
imageControl.MaxHeight = m_imageMaxSize.Height;
if (dataItem.ThumbnailImage.MediaItem == null)
imageControl.Field = "Image";
if (!string.IsNullOrEmpty(data["introduction"]))
introductionControl.Text = string.Format("<p>{0}</p>", data["introduction"].ToString().Replace("\n\r", "</p><p>"));
}
Also if you've got a list of Sitecore objects why don't you just bind that to the GridView, then in your RowDataBound method get the item back
var dataItem = e.Row.DataItem as Item;
and then do the logic in the BindEntries method in there, would prob be cleaner code and you wouldn't have to use stupid DataSets! Just an idea.

How to get radlistview items if you use paging

I'm using radlistview in my asp.net project . The problem that when I have to get all items of radlistview it return only items of the current page.
Example :
radlistview2.Items.ToList();
Output :
I got only 10 elements which are in the first page
My Question is :
How To get all items in radlistview ???
Please try with the below code snippet.
ASPX
<telerik:RadListView ID="RadListView1" runat="server" OnNeedDataSource="RadListView1_NeedDataSource" AllowPaging="true" PageSize="2">
<ItemTemplate>
<%# Eval("ID") %>
</ItemTemplate>
</telerik:RadListView>
<telerik:RadDataPager ID="RadDataPager1" runat="server" PagedControlID="RadListView1"
PageSize="2">
<Fields>
<telerik:RadDataPagerButtonField FieldType="FirstPrev"></telerik:RadDataPagerButtonField>
<telerik:RadDataPagerButtonField FieldType="Numeric"></telerik:RadDataPagerButtonField>
<telerik:RadDataPagerButtonField FieldType="NextLast"></telerik:RadDataPagerButtonField>
</Fields>
</telerik:RadDataPager>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
ASPX.CS
protected void RadListView1_NeedDataSource(object sender, RadListViewNeedDataSourceEventArgs e)
{
dynamic data1 = new[] {
new { ID = 1, Name ="Name_1",Customdate = DateTime.Now},
new { ID = 2, Name = "Name_2",Customdate = DateTime.Now},
new { ID = 3, Name = "Name_3",Customdate = DateTime.Now},
new { ID = 4, Name = "Name_4",Customdate = DateTime.Now},
new { ID = 5, Name = "Name_5",Customdate = DateTime.Now}
};
RadListView1.DataSource = data1;
}
protected void Button1_Click(object sender, EventArgs e)
{
int i = RadListView1.Items.Count();
RadListView1.AllowPaging = false;
RadListView1.Rebind();
int j = RadListView1.Items.Count();
//Access your count here
RadListView1.AllowPaging = true;
RadListView1.Rebind();
}

Repeater control not updating with ItemCommand

I have a Repeater control, that I have now reduced to just changing text in a text box when clicking the associated button.
However, this is not happening.
Here is my code so far:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<asp:Repeater ID="rptPdfList" runat="server" OnItemCommand="rptPdfList_ItemCommand">
<HeaderTemplate>
<table>
<tr>
<td>File Name</td>
<td></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblName" runat="server" Text=<%#Eval("FileName") %>></asp:Label>
</td>
<td>
<asp:Button ID="btnLoad" runat="server" Text="Load" CommandName="LoadDoc"/>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btnLoad" runat="server" Text="Load" OnClick="btnLoad_Click" /><br />
<iframe runat="server" id="pdfHolder"></iframe>
<br />
<asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetFiles();
}
private void GetFiles()
{
rptPdfList.DataSource = Pdf();
rptPdfList.DataBind();
}
protected void rptPdfList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
Label lblName = (Label)e.Item.FindControl("lblName");
switch (e.CommandName)
{
case "LoadDoc":
//xpdfHolder.Attributes.Add("src", "PDF/" + lblName.Text);
lblTest.Text = "test";
lblName.Text = "oops";
break;
}
}
public static List<PdfList> Pdf()
{
string pdfDir = HostingEnvironment.MapPath("~") + #"PDF\";
DirectoryInfo directory = new DirectoryInfo(pdfDir);
FileInfo[] pdfFiles = directory.GetFiles("*.pdf", SearchOption.AllDirectories);
List<PdfList> pdfLists = pdfFiles.Select(pdfFile => new PdfList
{
FileName = pdfFile.Name
}).ToList();
return pdfLists;
}
}
public class PdfList
{
public string FileName { get; set; }
}
Ca anyone see where I went wrong?
Edit, added all the code
Change this:
protected void Page_Load(object sender, EventArgs e)
{
GetFiles();
}
to this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GetFiles();
}
You are calling the GetFiles() each time so it is always returning to the initial state.
I am binding your repeater like this and it works fine for me, Just place your binding function in
if (!Page.IsPostBack)
condition :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (DataClassesDataContext dc = new DataClassesDataContext())
{
var v = (from s in dc.t_employees select s).ToList();
rptPdfList.DataSource = v;
rptPdfList.DataBind();
}
}
}
protected void rptPdfList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
Label lblName = (Label)e.Item.FindControl("lblName");
switch (e.CommandName)
{
case "LoadDoc":
//xpdfHolder.Attributes.Add("src", "PDF/" + lblName.Text);
lblTest.Text = "test";
lblName.Text = "oops";
break;
}
}

bind custom class array in repeater

I want to bind the CourseFee[] array to repeater.
I want to bind Amount and CourseFeeType.Descr in my repeater.
How do I bind it?
Sample Class
public class Order
{
public CourceFeeType FeeType;
public int Amount;
public int CourseFee;
public void AddFeeTypeDetails(CourceFeeType Fees)
{
FeeType = new CourceFeeType();
FeeType.Code = Fees.Code;
FeeType.Desc = Fees.Desc;
}
// Nested class
public class CourceFeeType
{
public String Code;
public String Desc;
}
}
Sample Form Load Code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Order> List = new List<Order>();
Order OrderObj = new Order();
Order.CourceFeeType Fees = new Order.CourceFeeType();
Fees.Code = "1";
Fees.Desc = "w2s";
OrderObj.Amount = 1;
OrderObj.AddFeeTypeDetails(Fees);
List.Add(OrderObj);
OrderObj = new Order();
OrderObj.Amount = 2;
Fees = new Order.CourceFeeType();
Fees.Code = "2";
Fees.Desc = "w22s";
OrderObj.AddFeeTypeDetails(Fees);
List.Add(OrderObj);
rpt.DataSource = List;
rpt.DataBind();
}
}
Repeater Item Bound Data Event Code
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label lbl = (Label)e.Item.FindControl("lblDescription");
lbl.Text = ((Order)e.Item.DataItem).FeeType.Desc;
Label lblAmount = (Label)e.Item.FindControl("lblAmount");
lblAmount.Text = ((Order)e.Item.DataItem).Amount.ToString();
}
}
Sample HTML
<asp:Repeater ID="rpt" runat="server" OnItemDataBound="rpt_ItemDataBound">
<HeaderTemplate>
<table>
<tr>
<td>
Amount
</td>
<td>
Description
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblAmount" runat="server"></asp:Label>
</td>
<td>
<asp:Label ID="lblDescription" runat="server"></asp:Label>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

Categories