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

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

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.

Display a header for each grouping of items in a repeater?

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

add values from listbox to database

I have a problem that the value of listbox don't add into the database.
i have a checkboxlist and listbox, first i want to add all selected checkbox value in listbox, it works successfuly, and then i want to add that data of listbox come form checkboxlist to database on button click event, it do not work so how to solve this.
<div id="contentwrapper" class="contentwrapper">
<div id="validation" class="subcontent">
<form class="stdform stdform2" style="border-top:solid 1px #ddd">
<p>
<label>Hotel Name</label>
<span class="field">
<asp:DropDownList ID="ddlHotel" runat="server">
</asp:DropDownList>
</span>
</p>
<p>
<fieldset class="fieldset">
<legend class="legend">Facilities</legend>
<div>
<asp:CheckBoxList ID="cblFacility" runat="server" DataTextField="FacilityName" DataValueField="FacilityID" TextAlign="Right" RepeatColumns="5">
</asp:CheckBoxList>
<div class="clear">
</div>
</div>
</fieldset>
</p>
<p class="stdformbutton">
<asp:Button ID="btnAdd" runat="server" CssClass="radius2" Text="Add" onclick="btnAdd_Click" />
</p>
</form>
</div><!--subcontent-->
</div><!--contentwrapper-->
<div id="Div1" class="contentwrapper">
<div id="Div2" class="subcontent">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<form class="stdform stdform" style="border-top:solid 1px #ddd">
<p>
<span class="field">
<asp:ListBox ID="lstFacility" runat="server" SelectionMode="Multiple"></asp:ListBox><br />
</span>
</p>
<p class="stdformbutton">
<asp:Button ID="btnSubmit" runat="server" CssClass="submit radius2" Text="Submit" onclick="btnSubmit_Click" />
</p>
</form>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div><!--subcontent-->
</div>
AND .cs file is :
protected void Page_Load(object sender, EventArgs e)
{
string myConnectionString = "my connection string";
if (Session["admin"] != null)
{
lblEmail.Text = Session["adminEmail"].ToString();
lblAdmin.Text = "Wel Come " + Session["admin"].ToString();
lblAdmin1.Text = "Wel Come " + Session["admin"].ToString();
}
else
{
Response.Redirect("Login.aspx");
}
if (!Page.IsPostBack)
{
if (Session["hotelID"] != null)
{
ddlHotel.SelectedValue = Session["hotelID"].ToString();
}
ddlHotel.DataSource = dalMST_Hotel.SelectAll(myConnectionString);
ddlHotel.DataTextField = "HotelName";
ddlHotel.DataValueField = "HotelID";
ddlHotel.DataBind();
ddlHotel.Items.Insert(0, "Select Hotel");
BindData();
}
}
private void BindData()
{
string myConnectionString = "my connection string";
cblFacility.DataSource = dalMST_Facility.SelectAll(myConnectionString);
cblFacility.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string s1 = string.Empty;
lstFacility.Items.Clear();
foreach (ListItem item in this.cblFacility.Items)
{
if (item.Selected)
{
lstFacility.Items.Add(item);
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string myConnectionString = "my connection string";
Page.Validate();
if (Page.IsValid)
{
DataTable dt = dalMST_FacilityTran.SelectAll(myConnectionString);
int cnt = dt.Rows.Count;
entMST_FacilityTran.HotelID = Convert.ToInt32(ddlHotel.SelectedValue);
entMST_FacilityTran.FacilityID = 0;
entMST_FacilityTran.Created = DateTime.Now;
entMST_FacilityTran.Modified = DateTime.Now;
#region Insert,Update
for (int i = 0; i < lstFacility.Items.Count; i++)
{
int flag = 0;
for (int j = 0; j < cnt; j++)
{
int hotelid = Convert.ToInt32(dt.Rows[j][2].ToString());
int facilityid = Convert.ToInt32(dt.Rows[j][1].ToString());
if (lstFacility.Items[i].Selected)
{
entMST_FacilityTran.FacilityID = Convert.ToInt32(lstFacility.Items[i].Value);
if (entMST_FacilityTran.HotelID == hotelid && entMST_FacilityTran.FacilityID == facilityid)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
}
if (flag == 0)
{
if (dalMST_FacilityTran.Insert(entMST_FacilityTran, myConnectionString))
{
//txtFacility.Text = "";
//Response.Redirect("AddFacility.aspx");
//return;
}
}
}
Response.Redirect("AddRoomCategory.aspx");
#endregion
}
}
There is problem related to update panel.
Use below code:
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
<asp:PostBackTrigger ControlID="btnSubmit" />
</Triggers>
So submit button cilck event will fire.
Thanks
First You have to remove Nested For Loop
String lstName;
for (int i= 0; i< listBoxEmployeeName.Items.Count;i++)
{
lstName=listBoxEmployeeName.Items[i].Text;//Here your value stored in lstName
//here continue you insert query
}

ASP.net best way to change links

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.

Categories