ASP.net best way to change links - c#

Given:
<div class="subMenu">
Products Categories Another
</div>
In my code behind, how would I programatically change the list of links in that div?
In my code behind I would have something along the lines of:
if(menuID == 0) {
// Display some links here
}else if(menuID == 1) {
// Display some links here
}else if(menuID == 2) {
// Display some links here
}
Sorry for the simplicity, just trying to learn.

A slightly more complex way:
<asp:repeater id="rptMenu" runat="server">
<itemTemplate>
<%# Eval("LinkName") %>
<itemTemplate>
</asp:repeater>
And then build up a list of links in the back end and bind them to the repeater.
public class MenuItem
{
public string LinkUrl { get; set; }
public string LinkName { get; set; }
}
public void Page_Load()
{
//GetMenuItems would populate this list, depending on your logic
List<MenuItem> menuItems = GetMenuItems(menuId);
rptMenu.DataSource = menuItems;
rptMenu.DataBind()
}
This has the advantage that you could maybe drive this from a database, and you can easily edit the output if you need to.

I think you should use Panel control and add Hyperlinks inside.
ASPX page:
<asp:Panel ID="TestPanel" CssClass="Submenu" runat="server">
</asp:Panel>
code behind:
switch (menuId)
{
case 0:
TestPanel.Controls.Add(new HyperLink { Text = "Test", NavigateUrl = "testUrl", CssClass="Sublink" });
TestPanel.Controls.Add(new HyperLink { Text = "Test2", NavigateUrl = "testUrl2", CssClass = "Sublink" });
break;
case 1:
TestPanel.Controls.Add(new HyperLink { Text = "xxx", NavigateUrl = "xxx", CssClass="Sublink" });
TestPanel.Controls.Add(new HyperLink { Text = "xxx", NavigateUrl = "xxx", CssClass = "Sublink" });
break;
case 2:
TestPanel.Controls.Add(new HyperLink { Text = "xxx", NavigateUrl = "xxx", CssClass = "Sublink" });
TestPanel.Controls.Add(new HyperLink { Text = "xxx", NavigateUrl = "xxx", CssClass = "Sublink" });
break;
default:
break;
}

I do not know if this is the best way - but it a way :)
[Serializable]
public class MyLinks
{
public string cLink;
public string cTitle;
}
public partial class Dokimes_StackOverFlow_AplesDokimes : System.Web.UI.Page
{
MyLinks [] MyLinksAre = {
new MyLinks{cLink = "products.aspx", cTitle = "products"},
new MyLinks{cLink = "ProductCat.aspx", cTitle = "catalog"},
new MyLinks{cLink = "Paradeigma.aspx", cTitle = "example"},
};
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder sRenderOnMe = new StringBuilder();
int menuID = 0;
switch (menuID)
{
case 0:
foreach (int i in new int[] { 0, 1 })
sRenderOnMe.AppendFormat("{1}", MyLinksAre[i].cLink, MyLinksAre[i].cTitle);
break;
default:
foreach (int i in new int[] { 0, 1, 2 })
sRenderOnMe.AppendFormat("{1}", MyLinksAre[i].cLink, MyLinksAre[i].cTitle);
break;
}
txtMenouRender.Text = sRenderOnMe.ToString();
}
}
On the page
<asp:Literal runat="server" ID="txtMenouRender"></asp:Literal>

Do you want a simple href tag or some asp.net controls?
<div class="subMenu">
<% if(menuID == 0) { %>
Products
<% } else if(menuID == 1) { %>
Categories
<% } else { %>
Another
<% } %>
</div>
You can put also controls:
<div class="subMenu">
<% if(menuID == 0) { %>
<asp:LinkButton ID="Test" runat="server" OnClick="Test_OnClick" class="subLink">Products</LinkButton>
<% } else if(menuID == 1) { %>
Categories
<% } else { %>
Another
<% } %>
</div>

A simple way:
<div class="subMenu">
<%= myLinks %>
</div>
if(menuID == 0) {
myLinks = "<a href='products.aspx' class='sublink'>Products</a>etc.. etc.. "
}else if(menuID == 1) {
myLinks = "<a href='products.aspx' class='sublink'>Products</a>etc.. etc.. "
}else if(menuID == 2) {
myLinks = "<a href='products.aspx' class='sublink'>Products</a>etc.. etc.. "
}
Add:
Protected myLinks as string = ""
below the class definition.

Related

highlight user in table html css asp net

I have this table in a repeater that lists all contacts from database, if the user clicks on a specific contact, that contact should be highlighted with blue background color. I have tried this code, but it does not work...!
ASPX:
<asp:Repeater runat="server" OnItemCommand="rptList_OnItemCommand" ID="rptList">
<HeaderTemplate>
<table id="tblListContact">
<tr id="tblRowContact">
<th>
<asp:Label runat="server" Text="TRNSLTName" />
</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<%# ContactId.HasValue && ContactId == Convert.ToInt32(Eval("ID"))? "<tr style='background-color: #67C6FA;'>" : "<tr>" %> // Shouldn't this code make it work?
<td>
<asp:LinkButton runat="server" CommandName="selectContact" CommandArgument='<%# Eval("ID") %>'><%# Eval("Name") %></asp:LinkButton>
</td>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
C#:
public long? ContactId
{
get
{
if (ViewState["ContactId"] == null)
{
return null;
}
return Convert.ToInt64(ViewState["ContactId"]);
}
set
{
ViewState["ContactId"] = value;
}
}
/// <summary>
/// Assigning commands to repeater.
/// </summary>
protected void rptList_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
var contactId = Convert.ToInt64(e.CommandArgument);
switch (e.CommandName)
{
case "selectContact":
divRead.Visible = true;
ContactId = contactId;
var getContact = _ecSystem.GetContact(contactId);
if (getContact != null)
{
lblName.Text = getContact.Name;
lblPhone.Text = getContact.PhoneNumber;
lblMobile.Text = getContact.Cellphone;
lblAdress.Text = getContact.Street;
lblNotes.Text = getContact.Notes;
lblPage.Text = getContact.Homepage;
lblEmail.Text = getContact.Email;
imgPhone.Visible = !string.IsNullOrEmpty(lblPhone.Text);
imgMobile.Visible = !string.IsNullOrEmpty(lblMobile.Text);
imgAddress.Visible = !string.IsNullOrEmpty(lblAdress.Text);
imgNotes.Visible = !string.IsNullOrEmpty(lblNotes.Text);
imgPage.Visible = !string.IsNullOrEmpty(lblPage.Text);
imgEmail.Visible = !string.IsNullOrEmpty(lblEmail.Text);
}
break;
case "deleteContact":
ContactId = contactId;
break;
case "noBtn":
divRead.Visible = true;
break;
case "yesBtn":
if (ContactId != null)
{
_ecSystem.DeleteContact(ContactId.Value);
}
ContactId = null;
Response.Redirect("Contact.aspx");
break;
case "editContact":
_editMode = true;
divAdd.Visible = true;
var contacts = _ecSystem.GetContact(contactId);
ViewState["ContactID"] = contactId;
ViewState["Contacts"] = contacts;
break;
}
}
/// <summary>
/// Sets datasource and databind to aspx page.
/// </summary>
public void RptDataBind()
{
var userId = UserID;
_ecSystem = new ExternalCatalog();
var contacts = _ecSystem.GetContacts(userId);
if (contacts != null && contacts.Length > 0)
{
rptList.DataSource = contacts;
}
if (!Page.IsPostBack)
{
rptList.DataBind();
}
}

ASP.NET WebForms Nested Repeater With LINQ Group Data Source

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();
}
}
}

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.

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