I have a website and when opening the page, reloading automatically infinite times.
How do I stop the page from reloading automatically infinite times?
This code is doing that reloading , when i commented this code the reloading not reload the page.
but i don't know how fix it .
any advise .
This is the html code
<h1>
Edit Project</h1>
<div id="Div3" class="entryRow">
<div class="title">
<asp:Label ID="Label8" runat="server" Text="Select Developer"></asp:Label>
</div>
<div class="entry">
<asp:DropDownList ID="ddldeveloperForEdit" runat="server" AppendDataBoundItems="true"
DataSourceID="EntityDataSource2" DataTextField="DeveloperName" DataValueField="DeveloperPK">
<asp:ListItem Text="Select Developer" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:EntityDataSource ID="EntityDataSource2" runat="server" ConnectionString="name=MyCBEntities"
DefaultContainerName="MyCBEntities" EntitySetName="Developer" Select="it.[DeveloperPK], it.[DeveloperName]"
OrderBy="it.[DeveloperName]">
</asp:EntityDataSource>
Select Project
<asp:DropDownList ID="ddlProjects" runat="server" AutoPostBack="true" AppendDataBoundItems="true" OnSelectedIndexChanged="ddlProjects_SelectedIndexChanged">
</asp:DropDownList>
//here this control <cc1:CascadingDropDown code when i comment it the reloading not happened, here the issue how fix it
<cc1:CascadingDropDown ID="CascProjects" PromptText="Select Project" PromptValue="0" Enabled="true"
ServiceMethod="GetProjectsListByDeveloper" ServicePath="~/WebServ/MyCBWebService.asmx"
Category="selProject" TargetControlID="ddlProjects" runat="server" ParentControlID="ddldeveloperForEdit">
</cc1:CascadingDropDown>
</div>
<div class="msg">
</div>
</div>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateDevelopers();
}
else
{
return;
}
}
private void PopulateDevelopers()
{
using (var db = new MyCBEntities())
{
if (ddlDevelopers.Items.Count > 0)
{
ddlDevelopers.ClearSelection();
ddlDevelopers.Items.Clear();
}
var developers = db.Developer.OrderBy(z => z.DeveloperName).ToList();
ddlDevelopers.Items.Add(new ListItem("Select Developer", "0-1"));
foreach (var developer in developers)
{
ddlDevelopers.Items.Add(new ListItem(developer.DeveloperName, developer.DeveloperPK.ToString()));
}
ddlDevelopers.SelectedIndex = 0;
}
}
This is the ServiceMethod="GetProjectsListByDeveloper"
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod]
public CascadingDropDownNameValue[] GetProjectsListByDeveloper(string knownCategoryValues, string category)
{
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
MyCBEntities db = new MyCBEntities();
string developerIdStr = "";
if (kv.Count > 0 && kv.ContainsKey("country"))
{
developerIdStr = kv["country"];
}
else if (kv.Count > 0 && kv.ContainsKey("undefined"))
{
developerIdStr = kv["undefined"];
}
int developerId;
int.TryParse(developerIdStr, out developerId);
List<CascadingDropDownNameValue> values =
new List<CascadingDropDownNameValue>();
if (developerId > 0)
{
var projectList = db.DevelopersProject.Where(z => z.DeveloperFK == developerId).ToList();
foreach (var project in projectList)
{
values.Add(new CascadingDropDownNameValue(project.ProjectName, project.DeveloperProjectPK.ToString()));
}
}
return values.ToArray();
}
Related
I am creating a quiz application in ASP.net (c#) and I currently have one question at a time displaying with the use of a datapager. However, when i move from question 1 to question 2 and then back to question 1 the radiobutton selection disappears.
EDIT - I now have the radio button retaining a selection whenever I move from next to previous, HOWEVER, If I chose radiobutton1 and then move on to question 2, It has radiobutton1 already selected, even though I am yet to answer that question. So for some reason whatever selection I make on question 1 is being duplicated to the other questions.
Question1 example
Question2 example
<body>
<form id="form1" runat="server">
<div>
<asp:ListView ID="lvCustomers" runat="server" GroupPlaceholderID="groupPlaceHolder1"
ItemPlaceholderID="itemPlaceHolder1" OnPagePropertiesChanging="OnPagePropertiesChanging" OnPreRender="ListPager_PreRender">
<LayoutTemplate>
<div id="itemPlaceHolder1" runat="server">
</div>
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvCustomers" PageSize="1">
<Fields>
<asp:NextPreviousPagerField runat="server" ButtonType="Link"
ShowFirstPageButton="false"
ShowPreviousPageButton="true"
ShowNextPageButton="false" />
<asp:NumericPagerField ButtonType="Link" />
<asp:NextPreviousPagerField ButtonType="Link"
ShowNextPageButton="true"
ShowLastPageButton="false"
ShowPreviousPageButton="false" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("QuestionID")%>'></asp:Label><br />
<asp:Label ID="Label1" runat="server" Text='<%#Eval("QuestionText")%>'></asp:Label><br />
<li>
<asp:RadioButton ID="Radio1" Text='<%#Eval("Answer1") %>' GroupName="radiobtns" EnableViewState="true" runat="server" />
</li>
<li>
<asp:RadioButton ID="Radio2" runat="server" GroupName="radiobtns" EnableViewState="true" Text='<%#Eval("Answer2") %>' />
</li>
<li>
<asp:RadioButton ID="Radio3" runat="server" GroupName="radiobtns" EnableViewState="true" Text='<%#Eval("Answer3") %>' />
</li>
<li>
<asp:RadioButton ID="Radio4" runat="server" GroupName="radiobtns" EnableViewState="true" Text='<%#Eval("Answer4") %>' />
</li>
<br />
</ItemTemplate>
</asp:ListView>
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</p>
</form>
</body>
</html>
namespace WebApplication2.WebForms
{
public partial class _1QuestionQuiz : System.Web.UI.Page
{
string userAns;
int QuestionID;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindListView();
if (Session["QuizID"] != null)
{
int QuizID = Convert.ToInt32(Session["QuizID"]);
}
}
}
protected void ListPager_PreRender(object sender, EventArgs e)
{
if (Session["DTSource"] != null)
{
lvCustomers.DataSource = Session["DTSource"];
lvCustomers.DataBind();
}
GetSelections();
}
private void BindListView()
{
SqlConnection conn = new SqlConnection();
string connString = ConfigurationManager.ConnectionStrings["test1ConnectionString"].ConnectionString;
SqlCommand Cmd = new SqlCommand();
conn.ConnectionString = connString;
conn.Open();
if (lvCustomers != null)
{
foreach (ListViewItem item in lvCustomers.Items)
{
Label lbl = (Label)item.FindControl("Label2");
if (lbl != null)
{
QuestionID = Convert.ToInt32(lbl.Text);
ViewState["qstion"] = QuestionID;
}
RadioButton rd1 = (RadioButton)item.FindControl("Radio1");
RadioButton rd2 = (RadioButton)item.FindControl("Radio2");
RadioButton rd3 = (RadioButton)item.FindControl("Radio3");
RadioButton rd4 = (RadioButton)item.FindControl("Radio4");
if (rd1.Checked)
{
userAns = rd1.Text;
ViewState["Radio1"] = rd1.Text;
}
else if (rd2.Checked)
{
userAns = rd2.Text;
ViewState["Radio2"] = rd2.Text;
}
else if (rd3.Checked)
{
userAns = rd3.Text;
ViewState["Radio3"] = rd3.Text;
}
else if (rd4.Checked)
{
userAns = rd4.Text;
ViewState["Radio4"] = rd4.Text;
}
SqlCommand comm = new SqlCommand("InsertSelections", conn);
comm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(comm);
SqlParameter p1 = new SqlParameter("Answer", userAns);
SqlParameter p2 = new SqlParameter("QuestionID", QuestionID);
SqlParameter p3 = new SqlParameter("QuizID", (Session["QuizID"]));
comm.Parameters.Add(p1);
comm.Parameters.Add(p2);
comm.Parameters.Add(p3);
comm.ExecuteNonQuery();
}
}
}
private void GetSelections()
{
foreach (ListViewItem item in lvCustomers.Items)
{
Label lbl = (Label)item.FindControl("Label2");
if (lbl != null)
{
QuestionID = Convert.ToInt32(lbl.Text);
}
RadioButton rd1 = (RadioButton)item.FindControl("Radio1");
RadioButton rd2 = (RadioButton)item.FindControl("Radio2");
RadioButton rd3 = (RadioButton)item.FindControl("Radio3");
RadioButton rd4 = (RadioButton)item.FindControl("Radio4");
//Try radiobutton 1 as a tester
if (rd1 != null)
{
if (lbl != null && ViewState["Radio1"] != null)
{
rd1.Checked = true;
}
}
if (rd2 != null)
{
if (lbl != null && ViewState["Radio2"] != null)
{
rd2.Checked = true;
}
}
if (rd3 != null)
{
if (lbl != null && ViewState["Radio3"] != null)
{
rd3.Checked = true;
}
}
if (rd4 != null)
{
if (lbl != null && ViewState["Radio4"] != null)
{
rd4.Checked = true;
break;
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Score.aspx", false);
}
protected void OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
(lvCustomers.FindControl("DataPager1") as DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
BindListView();
}
}
}
Try overriding LoadViewState and SaveViewState to maintain the state of your radio buttons. For example, try something like the following, and pull the values back out of ViewState wherever you need them:
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (ViewState["Radio1"] != null)
Radio1.Text = (int)ViewState["Radio1"];
...
}
protected override object SaveViewState()
{
ViewState["Radio1"] = Radio1.Text;
...
return base.SaveViewState();
}
I have a problem. I created a couple of custom DataControlFields because I need to display data that doesn't come from a DataSource on a DataGrid.
I managed to get the controls unto the GridView but I can't manage to solve a couple of issues.
My controls do not persist their values between postbacks. I have the markup sitting inside an UpdatePanel which I set to Conditional. I then configured my triggers, excluding those of the GridView. I also tried setting the UpdateMode to Always. I get the same behavior here.
Here is my markup:
<asp:UpdatePanel UpdateMode="Conditional" ID="reportchooserUpdatePanel" runat="server">
<ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ddlMonth" EventName="Load" />
<asp:PostBackTrigger ControlID="ddlMonth" EventName="SelectedIndexChanged" />
<asp:PostBackTrigger ControlID="ddlYear" EventName="DataBinding" />
<asp:PostBackTrigger ControlID="ddlYear" EventName="SelectedIndexChanged
<asp:PostBackTrigger ControlID="GenerateReportsButton" EventName="Click" />
</Triggers>
<table class="ms-formtable">
<tr>
<td class="ms-formlabel">
<asp:Label ID="MonthYearLabel" runat="server" Text=""></asp:Label>
</td>
<td class="ms-formbody align-right">
<asp:DropDownList OnSelectedIndexChanged="ddlMonth_SelectedIndexChanged" AutoPostBack="true" runat="server" ID="ddlMonth" OnLoad="ddlMonth_Load">
<asp:ListItem Value="1">Januar</asp:ListItem>
<asp:ListItem Value="2">Februar</asp:ListItem>
<asp:ListItem Value="3">März</asp:ListItem>
<asp:ListItem Value="4">April</asp:ListItem>
<asp:ListItem Value="5">Mai</asp:ListItem>
<asp:ListItem Value="6">Juni</asp:ListItem>
<asp:ListItem Value="7">Juli</asp:ListItem>
<asp:ListItem Value="8">August</asp:ListItem>
<asp:ListItem Value="9">September</asp:ListItem>
<asp:ListItem Value="10">Oktober</asp:ListItem>
<asp:ListItem Value="11">November</asp:ListItem>
<asp:ListItem Value="12">Dezember</asp:ListItem>
</asp:DropDownList>
</td>
<td class="ms-formbody align-right">
<asp:DropDownList OnSelectedIndexChanged="ddlYear_SelectedIndexChanged" AutoPostBack="true" OnDataBinding="ddlYear_DataBinding" ID="ddlYear" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td style="width:100%;" class="ms-formbody" colspan="3">
<asp:GridView AutoGenerateColumns="false" ShowHeaderWhenEmpty="true" CssClass="grid-view" Width="100%" ID="gvProjects" runat="server">
</asp:GridView>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td class="ms-formtoolbar align-right" colspan="3">
<asp:HyperLink Target="_blank" Font-Size="X-Small" ID="hlGembox" NavigateUrl="http://www.gemboxsoftware.com/spreadsheet/free-version" runat="server"></asp:HyperLink>
<asp:Button OnClientClick="AddNotification('Please wait...')" ID="GenerateReportsButton" runat="server" Text="" OnClick="GenerateReportsButton_Click" />
</td>
<td></td>
<td></td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
And here is the code of one of my custom DataControlFields. They are basically the same except for the controls they display:
class TemplateDropDownControl : DataControlField
{
SPList reportslist = ListItemHelper.GetReportsList();
protected void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
{
string ID = Guid.NewGuid().ToString();
DropDownList list = new DropDownList();
list.ID = ID;
FillContentTypeDropDown(list);
cell.Controls.Add(list);
}
public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
{
//Call the base method.
base.InitializeCell(cell, cellType, rowState, rowIndex);
this.InitializeDataCell(cell, rowState);
}
protected override DataControlField CreateField()
{
return new BoundField();
}
public string DataField
{
get
{
object value = base.ViewState["DataField"];
if (value != null)
{
return value.ToString();
}
else
{
return string.Empty;
}
}
set
{
base.ViewState["DataField"] = value;
this.OnFieldChanged();
}
}
public override void ExtractValuesFromCell(System.Collections.Specialized.IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
{
DropDownList list = cell.Controls[0] as DropDownList;
ListItem selectedValue = list.SelectedItem;
if (dictionary.Contains(DataField))
dictionary[DataField] = selectedValue.Value;
else
dictionary.Add(DataField, selectedValue.Value);
}
private void FillContentTypeDropDown(DropDownList ddlContentTypes)
{
if (reportslist == null)
return;
SPContentTypeCollection cts = reportslist.ContentTypes;
ddlContentTypes.Items.Clear();
foreach (SPContentType ct in cts)
{
ddlContentTypes.Items.Add(new ListItem() { Text = ct.Name, Value = ct.DocumentTemplateUrl + ct.DocumentTemplate.Replace("~site", "") });
}
}
}
And lastly, here is the code where I add these to my page. I set the AutoGenerateColumns property of the GridView to false in markup:
private void BindDataGrid()
{
DataTable table = new DataTable();
table = new DataTable();
table.Columns.Add(ResourceHelper.LoadResource(ResourceName.ProjectnumberTableString));
table.Columns.Add(ResourceHelper.LoadResource(ResourceName.TemplateString));
table.Columns.Add(ResourceHelper.LoadResource(ResourceName.FileFormatString));
gvProjects.Columns.Clear();
gvProjects.DataSource = null;
//Fill DataTable here...
BoundField projectnumberField = new BoundField();
projectnumberField.HeaderText = ResourceHelper.LoadResource(ResourceName.ProjectnumberTableString);
projectnumberField.DataField = ResourceHelper.LoadResource(ResourceName.ProjectnumberTableString);
FileFormatCheckboxControl checkBoxControl = new FileFormatCheckboxControl();
checkBoxControl.DataField = ResourceHelper.LoadResource(ResourceName.FileFormatString);
checkBoxControl.HeaderText = ResourceHelper.LoadResource(ResourceName.FileFormatString);
TemplateDropDownControl dropDownControl = new TemplateDropDownControl();
dropDownControl.DataField = ResourceHelper.LoadResource(ResourceName.TemplateString);
dropDownControl.HeaderText = ResourceHelper.LoadResource(ResourceName.TemplateString);
gvProjects.Columns.Add(projectnumberField);
gvProjects.Columns.Add(dropDownControl);
gvProjects.Columns.Add(checkBoxControl);
gvProjects.DataSource = table;
gvProjects.DataBind();
}
Anybody know what I'm doing wrong here?
EDIT: Maybe I should be mentioning that I display the form in a Sharepoint modal dialog.
Ok I solved it another way since I had not idea why my problem kept happening. I just use a asp:Table now and generate the whole thing from code-behind. I have one method for this which I call on every page postback. It's important to note to call this method only from Page_Load. It didn't work when I called it from Page_Init.
Here is my code:
private void BindDataGrid()
{
GenerateReportsButton.Enabled = true;
reportsTable.Rows.Clear();
TableHeaderRow headerrow = new TableHeaderRow();
TableHeaderCell pnumberheader = new TableHeaderCell();
TableHeaderCell templateheader = new TableHeaderCell();
TableHeaderCell fileFormatHeader = new TableHeaderCell();
pnumberheader.Text = ResourceHelper.LoadResource(ResourceName.ProjectnumberTableString);
templateheader.Text = ResourceHelper.LoadResource(ResourceName.TemplateString);
fileFormatHeader.Text = ResourceHelper.LoadResource(ResourceName.FileFormatString);
headerrow.Cells.Add(pnumberheader);
headerrow.Cells.Add(templateheader);
headerrow.Cells.Add(fileFormatHeader);
reportsTable.Rows.Add(headerrow);
if (ddlYear.SelectedItem == null || ddlMonth.SelectedItem == null)
{
int index = reportsTable.Rows.Add(new TableRow());
TableCell cell = new TableCell();
cell.ColumnSpan = 3;
cell.Text = ResourceHelper.LoadResource(ResourceName.NoListItemsForMonthYear);
reportsTable.Rows[index].Cells.Add(cell);
GenerateReportsButton.Enabled = false;
return;
}
//Get items here
if (items.Count == 0)
{
int index = reportsTable.Rows.Add(new TableRow());
TableCell cell = new TableCell();
cell.ColumnSpan = 3;
cell.Text = ResourceHelper.LoadResource(ResourceName.NoListItemsForMonthYear);
reportsTable.Rows[index].Cells.Add(cell);
GenerateReportsButton.Enabled = false;
return;
}
else
InsertRowIntoProjectTable("Intern", "Intern");
List<string> processedReports = new List<string>();
foreach(SPListItem item in items)
{
if (item[Variables.projectNumberField].ToString() != "Intern" && !processedReports.Contains(item[Variables.activityProject].ToString()))
{
InsertRowIntoProjectTable(item[Variables.activityProject].ToString(), item.ID.ToString());
processedReports.Add(item[Variables.activityProject].ToString());
}
}
}
Then you can just read the data like this:
foreach(TableRow row in reportsTable.Rows)
{
//Important since foreach also iterates over headerrow
if (row.Cells[1].Controls.Count > 0 && row.Cells[1].Controls[0] is DropDownList)
{
string value1= row.Cells[0].Text;
string value2= ((DropDownList)row.Cells[1].Controls[0]).SelectedValue;
//do stuff with the data
}
}
If anybody still finds the answer to my specific problem above, feel free to add it. I will mark it as accepted once verified that it works.
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.
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
}
I have a datalist
<asp:DataList ID="dlstImage" runat="server" RepeatDirection="Horizontal" RepeatColumns="5"
CellSpacing="8">
<ItemTemplate>
<asp:ImageButton ID="Image" runat="server" ImageUrl='<%#"~/Controls/ShowImage.ashx?FileName=" +DataBinder.Eval(Container.DataItem, "FilePath") %>'
OnCommand="Select_Command" CommandArgument='<%# Eval("Id").ToString() +";"+Eval("FilePath")+";"+Eval("Index") %>' /><br />
<asp:Label ID="lbl" runat="server" Text="Figure"></asp:Label><%# dlstImage.Items.Count + 1%>
</ItemTemplate>
</asp:DataList>
In which i am binding the image after uploading through uplodify upload, now i have one more datalist
and two btn up and down,
<asp:ImageButton ID="ibtnMoveUp" runat="server" ImageUrl="~/App_Themes/Default/Images/moveup.bmp"
Style="height: 16px" ToolTip="MoveUp The Item" />
<asp:ImageButton ID="ibtnMoveDown" runat="server" ImageUrl="~/App_Themes/Default/Images/movedown.bmp"
ToolTip="MoveDown The Item" />
<asp:DataList ID="dlstSelectedImages" runat="server" RepeatDirection="Horizontal"
RepeatColumns="5" CellSpacing="8">
<ItemTemplate>
<asp:ImageButton ID="Image" runat="server" /><br />
<asp:Label ID="lbl" runat="server" Text="Figure"></asp:Label><%# dlstImage.Items.Count + 1%>
</ItemTemplate>
</asp:DataList>
My both datalist is in the same webuser control, datalist1 and datalist2 and I have 2 btn up and down, when i select one image from datalist1 and click on down btn then the selected image should move to datalist2. How to do that? someone please help me,
You need to handle the ItemCommand event of one DataList in which you have to copy the selected data (image) into another dataSource of two DataList and remove that item from the datasource of one DataList.
Markup:
<asp:DataList
ID="DataList1"
runat="server"
OnItemCommand="PerformMove"
>
<ItemTemplate>
<br /><%#Eval("Text") %>
<asp:Button ID="btn1"
runat="server"
Text="Move"
CommandName="cmd"
CommandArgument='<%#Eval("Text") %>'
/>
</ItemTemplate>
</asp:DataList>
<asp:DataList ID="DataList2" runat="server">
<ItemTemplate>
<br /><%#Eval("Text") %>
</ItemTemplate>
</asp:DataList>
Code-behind (.cs)
public class Data
{
public string Text { get; set; }
public override int GetHashCode()
{
return Text.GetHashCode();
}
public override bool Equals(object obj)
{
return GetHashCode() == obj.GetHashCode();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Data> list1 = new List<Data >()
{
new Data() { Text="One"},
new Data() { Text="Two"},
new Data() { Text="Three"},
};
List<Data> list2 = new List<Data>();
Session["list1"] = list1;
Session["list2"] = list2;
DataList1.DataSource = Session["list1"];
DataList1.DataBind();
DataList2.DataSource = Session["list2"];
DataList2.DataBind();
}
}
protected void PerformMove(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "cmd")
{
List<Data> list1 = Session["list1"] as List<Data>;
List<Data> list2 = Session["list2"] as List<Data>;
list1.Remove(new Data() { Text=e.CommandArgument.ToString() });
list2.Add(new Data() { Text = e.CommandArgument.ToString() });
DataList1.DataSource = Session["list1"];
DataList1.DataBind();
DataList2.DataSource = Session["list2"];
DataList2.DataBind();
}
}
I am using this code and its working well for me.
ArrayList ImgArry = new ArrayList();
path = objGetBaseCase.GetImages(TotImgIds);
ImgArry.Add(SelImgId);
ImgArry.Add(SelImgpath);//image name
ImgArry.Add(SelImgName);//image path
//path.Remove(ImgArry);
List<ArrayList> t = new List<ArrayList>();
if (newpath.Count > 0)
t = newpath;
t.Add(ImgArry);
newpath = t;
for (int i = 0; i < newpath.Count; i++)
{
ArrayList alst = newpath[i];
newtb.Rows.Add(Convert.ToInt32(alst[0]), alst[1].ToString(), alst[2].ToString(), i);
}
dlstSelectedImages.DataSource = newtb;
DataBind();
path = objGetBaseCase.GetImages(TotImgIds);
for (int i = 0; i < path.Count; i++)
{
ArrayList alst = path[i];
tb.Rows.Add(Convert.ToInt32(alst[0]), alst[1].ToString(), alst[2].ToString(), i);
}
dlstImage.DataSource = tb;
DataBind();