Display a header for each grouping of items in a repeater? - c#

I have an product order review page that displays a list of whatever the user has entered. What is needed is the name of the location that each product or product grouping belongs to (i.e. If the user selected 3 products from under the "Desks" listing, those three products should appear under the header "Desks" on the order review page. If the user purchased 5 items from under the "Lobbies" listing, then those 5 products should appear under the header "Lobbies" on the order review page).
Currently, I can get the correct header text, but the text repeats itself with each item (i.e. The header "Desks" appears above each of the 3 items ordered under the "Desks" listing). I would like it to appear only once per item/grouping of items but I am not sure how to do it.
I am using a repeater to display the order information to the user, and everything else is working the way I want it. It's just this little bit I'm confused about. Any help would be great. Thanks in advance!
Here is the designer code:
<asp:Repeater ID="orderRepeater" runat="server" >
<itemtemplate>
<h3 class="locationName"><%# Eval("LocationName") %></h3>
<div class="headerRow">
<div class="header">
<div class="thumb"><p></p></div>
<div class="headerField name"><p class="hField">Product</p></div>
<div class="headerField sku"><p class="hField">GOJO SKU</p></div>
<div class="headerField size"><p class="hField">Size</p></div>
<div class="headerField case"><p class="hField">Case Pack</p></div>
<div class="headerField qty"><p class="hField">Quantity</p></div>
</div>
</div>
<div class="table">
<div class="row">
<div class="thumb"><%# Eval("Thumbnail") %></div>
<div class="field name"><p class="pField"> <%#Eval("ProductName") %> </p></div>
<div class="field sku"><p class="pField"> <%#Eval("Sku") %></p></div>
<div class="field size"><p class="pField"> <%#Eval("Size") %></p></div>
<div class="field case"><p class="pField"><%#Eval("CasePack") %></p></div>
<div class="field qty"><p class="pField"><%#Eval("Qty") %></p></div>
</div>
</div>
</itemtemplate>
</asp:Repeater>
Here is the code behind:
private void Page_Load(object sender, EventArgs e)
{
Label lbl = (Label)FindControl("orderLbl");
Item CurrentItem = Sitecore.Context.Item;
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoMarket");
if (Session["orderComplete"] != null && Session["orderComplete"] != "")
{
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='gojoMarketOfficeBuildigProductMap']/*[##templatename='gojoOrderReview']");
Database db = Sitecore.Context.Database;
DataSet dset = new DataSet();
if (ProductGroup != null)
{
string InFromSession = Session["orderComplete"].ToString();
try
{
DataTable summary = dset.Tables.Add("summary");
summary.Columns.Add("LocationName", Type.GetType("System.String"));
summary.Columns.Add("Thumbnail", Type.GetType("System.String"));
summary.Columns.Add("ProductName", Type.GetType("System.String"));
summary.Columns.Add("Sku", Type.GetType("System.String"));
summary.Columns.Add("Size", Type.GetType("System.String"));
summary.Columns.Add("CasePack", Type.GetType("System.String"));
summary.Columns.Add("Qty", Type.GetType("System.String"));
summary.Columns.Add("Location", Type.GetType("System.String"));
Label qL = (Label)FindControl("qty");
string[] orders = InFromSession.Split(';');
foreach (string order in orders)
{
int total = orders.GetUpperBound(0);
if (order != "")
{
string[] infos = order.Split(',');
string ids = infos.GetValue(0).ToString();
string qtys = infos.GetValue(1).ToString();
if (ids != "")
{
Item CatalogueItem = db.Items[ids];
DataRow drow = summary.NewRow();
Item LocationItem = ScHelper.FindAncestor(CatalogueItem, "gojoProductLocation");
if (LocationItem != null)
{
//this returns the header text values that I need
string LocationName = LocationItem.Fields["Header"].ToString();
drow["LocationName"] = LocationName;
}
Item orderItem = db.Items[CatalogueItem.Fields["Reference SKU"].Value];
if (orderItem != null)
{
Item marketItem = db.Items[orderItem.Fields["Master Product"].Value];
if (marketItem != null)
{
Item CPNItem = db.Items[marketItem.Fields["Complete Product Name"].Value];
drow["Thumbnail"] = "";
Sitecore.Data.Fields.XmlField fileField = marketItem.Fields["Thumbnail"];
drow["Thumbnail"] = "<image src=\"" + ScHelper.GetCorrectFilePath(fileField) + "\" border=\"0\" alt=\"\">";
if (CPNItem != null)
{
var name = CPNItem["Complete Name"];
drow["ProductName"] = name;
}
drow["Sku"] = marketItem.Fields["SKU"].Value;
drow["CasePack"] = marketItem.Fields["Case Pack"].Value;
if (marketItem.Fields["Size"] != null)
{
drow["Size"] = marketItem.Fields["Size"].Value;
}
else
{
drow["Size"] = "N/A";
}
drow["Qty"] = qtys.ToString();
summary.Rows.Add(drow);
}
}
}
}
}
orderRepeater.DataSource = dset;
orderRepeater.DataMember = "summary";
orderRepeater.DataBind();
}
catch (Exception x)
{
Response.Write(x.Message.ToString());
}
}
}
}
else
{
HyperLink none = (HyperLink)FindControl("link");
Label msg = (Label)FindControl("msgLbl");
none.Visible = true;
msg.Text = "You have not selected any items for purchase. To purchase items, please visit our complete product listing: ";
}
}

I'd put the header in the <HeaderTemplate>. So it'd look like:
<asp:Repeater ID="orderRepeater" runat="server" >
<HeaderTemplate><h3><asp:Literal runat="server" id="header" /></h3></HeaderTemplate>
<ItemTemplate>[your existing code here]</ItemTemplate>
</asp:Repeater>
And in code behind do something like:
protected void orderRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
((Literal)e.Item.FindControl("header")).Text = "The header" // Whatever you would like this to be;
}
}

Related

Use Hyperlink in code

how can i use a asp:hyperlink in my code where the user can press the number and go to another page, so this is my code,
if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
loggedin.Text = "Registered users today: " + dr["RegisteredUsersToday"];
}
if (dtParent != null)
{
foreach (DataRow dr in dtParent.Rows)
{
loggedinParents.Text = "Registered Parents today: " + dr["RegisteredUsersToday"];
}
}
else
{
loggedinParents.Text = "Registered Parents today: 0 ";
}
if (dtTeacher != null)
{
foreach (DataRow dr in dtTeacher.Rows)
{
loggedinTeachers.Text = "Registered Teachers today: " + dr["RegisteredUsersToday"];
}
}
else
{
loggedinTeachers.Text = "Registered Teachers today: 0 ";
}
if (dtStudents != null)
{
foreach (DataRow dr in dtStudents.Rows)
{
loggedinStudents.Text = "Registered Students today: " + dr["RegisteredUsersToday"];
}
}
else
{
loggedinStudents.Text = "Registered Students today: 0 ";
}
}
else
{
loggedin.Text = "No new users today";
}
i want the hyperlink to be between RegisteredUsersToday, and this is my html where a have created the labels,
<div class="panel panel-default">
<div class="text-center panel-heading">
<a data-toggle="collapse" href="#collapse1" >
<asp:Label runat="server" ID="loggedin"></asp:Label>
</a>
</div>
<br />
<div id="collapse1" class="panel-collapse collapse">
<div class="text-center">
<asp:Label runat="server" ID="loggedinParents"></asp:Label>
</div>
<br />
<div class="text-center">
<asp:Label runat="server" ID="loggedinTeachers"></asp:Label>
</div>
<br />
<div class="text-center">
<asp:Label runat="server" ID="loggedinStudents"></asp:Label>
</div>
</div>
</div>

How to display database values in div

I am trying to get values from database and display it in a div.
here I am getting values from mysql database and I have HTML in .aspx page. I have 20 records and I want to print the data in different divs.
how can I do it using for loop.
HTML:
<div class="col-xs-12 col-sm-5 col-md-5 col-lg-3">
<div class="panel panel-warning">
<div class="panel-heading">Animal Name here</div>
<div class="panel-body">Animal image</div>
</div>
</div>
C#:
protected void Page_Load(object sender, EventArgs e)
{
try
{
string scon = "SERVER=localhost;DATABASE=animal_adoption_site;UID=root;";
MySqlConnection con = new MySqlConnection(scon);
String s = "select animal_pet_name,animal_donation_plan,animal_image_uploaded from animal_details";
MySqlDataAdapter dat = new MySqlDataAdapter(s, con);
}
catch (Exception ex)
{
string s = ex.ToString();
Response.Write(s);
}
}
You can do something like
Imagine in the server you have the following
public List<string> MyItems { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
MyItems = new List<string>();
MyItems.Add("Item 1");
MyItems.Add("Item 2");
MyItems.Add("Item 3");
MyItems.Add("Item 4");
}
In the client you can do a for loop for the items
<% foreach (string myItem in MyItems)
{ %>
<div class="col-xs-12 col-sm-5 col-md-5 col-lg-3">
<div class="panel panel-warning">
<div class="panel-heading"><%: myItem %></div>
<div class="panel-body">Animal image</div>
</div>
</div>
<%} %>

how to get all tweets on hashtag using Tweetsharp

How can I get all tweets on behalf of specific hashtag/keyword and display it on View page? The only solution found returns a null exception.
public ActionResult TweetView(string txtTwitterName)
{
//TwitterService("consumer key", "consumer secret");
var service = new TwitterService("", "");
//AuthenticateWith("Access Token", "AccessTokenSecret");
service.AuthenticateWith("", "");
TwitterSearchResult tweets = service.Search(new SearchOptions { Q = txtTwitterName, SinceId=29999 });
IEnumerable<TwitterStatus> status = tweets.Statuses;
ViewBag.Tweets = tweets;
return View();
}
View :
IEnumerable<TwitterStatus> tweets = ViewBag.Tweets as IEnumerable<TwitterStatus>;
foreach (var tweet in tweets)
{
<div class="tweet">
<div class="picture">
<img src="#tweet.User.ProfileImageUrl" alt="#tweet.User.ScreenName" title="#tweet.User.ScreenName" />
</div>
<div class="info">
<span>#tweet.User.Name, #tweet.User.Description - #tweet.User.Location </span>
<br />
<a href="https://twitter.com/statuses/#tweet.Id" class="text">
#tweet.Text
</a>
<div class="action">
#tweet.CreatedDate.AddHours(3).ToString("d/M/yyyy HH:mm:ss")
</div>
</div>
<div class="clear">
</div>
</div>
}
for the null value, in your view :
IEnumerable<TwitterStatus> status = ViewBag.Tweets as IEnumerable<TwitterStatus>;
if(status != null )
{
foreach (var tweet in status)
{
<div class="tweet">
<div class="picture">
<img src="#tweet.User.ProfileImageUrl" alt="#tweet.User.ScreenName"
title="#tweet.User.ScreenName" />
</div>
<div class="info">
<span>#tweet.User.Name, #tweet.User.Description - #tweet.User.Location </span>
<br />
<a href="https://twitter.com/statuses/#tweet.Id" class="text">
#tweet.Text
</a>
<div class="action">
#tweet.CreatedDate.AddHours(3).ToString("d/M/yyyy HH:mm:ss")
</div>
</div>
<div class="clear">
</div>
</div>
}
}
and for your Controller, modify the last code by :
ViewBag.Tweets = status;
I hope this post will help, thx :)
I struggled with the same problem. Here is my vague solution. The function will return whenever your required number of tweets are returned. I hope it helps you.
string maxid = "1000000000000"; // dummy value
int tweetcount = 0;
if (maxid != null)
{
var tweets_search = twitterService.Search(new SearchOptions { Q = keyword, Count = Convert.ToInt32(count) });
List<TwitterStatus> resultList = new List<TwitterStatus>(tweets_search.Statuses);
maxid = resultList.Last().IdStr;
foreach (var tweet in tweets_search.Statuses)
{
try
{
ResultSearch.Add(new KeyValuePair<String, String>(tweet.Id.ToString(), tweet.Text));
tweetcount++;
}
catch { }
}
while (maxid != null && tweetcount < Convert.ToInt32(count))
{
maxid = resultList.Last().IdStr;
tweets_search = twitterService.Search(new SearchOptions { Q = keyword, Count = Convert.ToInt32(count), MaxId = Convert.ToInt64(maxid) });
resultList = new List<TwitterStatus>(tweets_search.Statuses);
foreach (var tweet in tweets_search.Statuses)
{
try
{
ResultSearch.Add(new KeyValuePair<String, String>(tweet.Id.ToString(), tweet.Text));
tweetcount++;
}
catch { }
}
}
}

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.

Databinding custom objects to controls in aspx file and not code behind

I'm having issues fully binding a generic list in aspx file. Although It binds to my <p> and <h> tags properly but not my ImageButton. I'm I doing something wrong here. Below is my code
Aspx File
<%
int count = 1;
for (item = 0; item < mList.Count; AddItem())
{
if (count == 3)
{ %>
<div class="one_third_last">
<% count = 0;
}
else
{ %>
<div class="one_third">
<%}
count++;%>
<div class="modern_img_frame modern_four_col_large">
<div class="preload_four_col_large">
<div class="attachment-fadeIn">
<asp:ImageButton ID="ImageButton" runat="server" ImageUrl="~/images2/premium-website-template-2.jpg"
ToolTip="CSS Template" AlternateText="CSS Template" Width="190" Height="111"
CommandName="<%# mList[item].PaymentCode %>" CommandArgument="<%# mList[item].PaymentDescription %>"
OnCommand="ImageButton_Command" />
</div>
</div>
</div>
<!-- end modern_img_frame -->
<h6>
<%= mList[item].PaymentDescription%></h6>
<p>
<%= mList[item].PaymentDescription%></p>
</div>
<%
} %>
Code Behind
protected List<Payments_Default> mList;
protected int item;
public String PaymentCode { get; set; }
public String PaymentDescription { get; set; }
public int PaymentNumber { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
mList = new Payments_Default().GetPaymentTypes();
this.DataBind();
}
protected void AddItem()
{
item++;
}
protected List<Payments_Default> GetPaymentTypes()
{
List<Payments_Default> mList = new List<Payments_Default>();
Payments_Default mObject = null;
SqlCommand command = GenericSqlDataAccess.CreateCommandOnline("Text");
command.CommandText = "SELECT bla bla bla";
DataTable table = new DataTable();
table = GenericSqlDataAccess.ExecuteReader(command);
foreach (DataRow row in table.Rows)
{
mObject = new Payments_Default();
mObject.PaymentCode = row["PayTypeCode"].ToString();
mObject.PaymentDescription = row["PayTypeDesc"].ToString();
mObject.PaymentNumber = table.Rows.Count;
mList.Add(mObject);
}
return mList;
}

Categories