Sitecore Feed latest 2 items - c#

I have a sitecore web part that I am trying to get to display the top 2 most current items by date. I am having trouble because I am only able to get the latest item to show.
For the ascx Code:
<asp:Repeater ID="newsContainer" runat="server">
<ItemTemplate>
<div class="newsItem">
<h2>News</h2>
<a href="<%# SitecoreUtility.NavigateUrl((Item)Container.DataItem)%>" class="newsHeadline">
<span> <sc:Date ID="Date1" Item="<%# Container.DataItem %>" Field="Posted-Date" Format="MM.dd.yyyy" runat="server" />
<sc:Text ID="Text1" Item="<%# Container.DataItem %>" Field="Title" runat="server" />
</span>
</a>
<!-- <p class="newsSummary">
<asp:Literal ID="litBody" runat="server" Text="<%# SitecoreUtility.TruncateByWords(((Item)Container.DataItem).Fields[Constants.Fields.BODY].Value, 20) %>"></asp:Literal>
...
+ More</p> -->
</div>
</ItemTemplate>
</asp:Repeater>
<asp:Panel ID="pnlPagination" runat="server"></asp:Panel>
<asp:Panel ID="pnlArchive" runat="server">
<!-- <div class="newsArchiveLink">
View Archived News
</div> -->
</asp:Panel>
<asp:Panel ID="pnlCurrent" runat="server">
<div class="newsArchiveLink">
View Current News
</div>
</asp:Panel>
For the ASCX.CS File:
public partial class Homepage_NewsListing : BaseSublayout
{
int CurrentPage = 1;
int PageSize = Constants.Values.SEARCH_SMALL_LIST;
protected void Page_Load(object sender, EventArgs e)
{
CurrentPage = int.Parse(WebUtil.GetQueryString("page", "1"));
List<Item> newsListings = new List<Item>();
Item newsItems = SitecoreUtility.Db.GetItem(Constants.Items.NEWS);
if (WebUtil.GetQueryString("type", "") == "archive")
{
newsListings = newsItems.Children.Where(item =>
(SitecoreUtility.FormatDateAtMidnight(item, Constants.Fields.ARCHIVEDATE) <= DateTime.Now)
&&
(!string.IsNullOrEmpty(item.Fields[Constants.Fields.ARCHIVEDATE].Value))
).OrderBy(item => item.Fields[Constants.Fields.POSTED_DATE].Value).ToList();
pnlArchive.Visible = false;
//pnlCurrent.Visible = true;
pnlCurrent.Visible = false;
}
else
{
newsListings = newsItems.Children.Where(item =>
(SitecoreUtility.FormatDateAtMidnight(item, Constants.Fields.ARCHIVEDATE) > DateTime.Now)
||
(string.IsNullOrEmpty(item.Fields[Constants.Fields.ARCHIVEDATE].Value))
).OrderBy(item => item.Fields[Constants.Fields.POSTED_DATE].Value).ToList();
//pnlArchive.Visible = true;
pnlArchive.Visible = false;
pnlCurrent.Visible = false;
}
newsContainer.DataSource = DisplayResults(newsListings.OrderByDescending(item => item.Fields[Constants.Fields.POSTED_DATE].Value).ToList());
newsContainer.DataBind();
}
protected List<Item> DisplayResults(List<Item> results)
{
pnlPagination.Controls.Add(new Pager(results.Count, PageSize, CurrentPage).BuildPaging());
if (CurrentPage > 1)
return results.Skip((CurrentPage - 1) * PageSize).Take(PageSize).ToList();
return results.Take(PageSize).ToList();
}
}

I would first try to make your code a bit more simple (for debugging) and use a fast query to pull items within a date range.
var date = DateTime.Now.AddMonths(3);
var dateString = date.Year.ToString() + date.Month.ToString().PadLeft(2, '0') + date.Day.ToString().PadLeft(2, '0');
var newsList = Sitecore.Context.Database.SelectItems("fast:/sitecore/content/home/your-path-to-news/*[##templatename='Your template name' and #POSTED_DATE > '" + dateString + "']").ToList();
newsList = newsList.OrderByDescending(n => n.Fields["POSTED_DATE"].Value).Take(2).ToList();
newsContainer.DataSource = newsList;
newsContainer.DataBind();

Related

How to split datetime and display on each dropdownlist column in C# aspnet

I have a TimeTable table and a Product table. Each product will have 4 timetable.
At my update product page, it should able to retrieve the latest timetable and split every timetable into respective dropdown list. Currently when i click update page, it only show the null calendar which is not I want. I want the calender to populate with the database time. My idea was to split the [day] [time] [am/pm] and then push to the dropdown list, But I do not know how can I achieve that. Anyone willing to guide me will be much appreciate thank you.
aspx
<tr>
<td>
<label class="col-sm-2 control-label">Timetable1:</label>
</td>
<td>
<div class="auto-style1">
<label>Every</label>
<asp:DropDownList ID="weekTime1" runat="server">
<asp:ListItem>Monday</asp:ListItem>
<asp:ListItem>Tuesday</asp:ListItem>
<asp:ListItem>Wednesday</asp:ListItem>
<asp:ListItem>Thursday</asp:ListItem>
<asp:ListItem>Friday</asp:ListItem>
<asp:ListItem>Saturday</asp:ListItem>
<asp:ListItem>Sunday</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="startTime1" runat="server">
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="startAP1" runat="server">
<asp:ListItem>AM</asp:ListItem>
<asp:ListItem>PM</asp:ListItem>
</asp:DropDownList>
<label>- </label>
<asp:DropDownList ID="endTime1" runat="server">
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="endAP1" runat="server">
<asp:ListItem>AM</asp:ListItem>
<asp:ListItem>PM</asp:ListItem>
</asp:DropDownList>
</div>
</td>
</tr>
<tr>
<td>
<label class="col-sm-2 control-label">Timetable2:</label>
</td>
<td>
<div class="auto-style1">
<label>Every</label>
<asp:DropDownList ID="weekTime2" runat="server">
<asp:ListItem>Monday</asp:ListItem>
<asp:ListItem>Tuesday</asp:ListItem>
<asp:ListItem>Wednesday</asp:ListItem>
<asp:ListItem>Thursday</asp:ListItem>
<asp:ListItem>Friday</asp:ListItem>
<asp:ListItem>Saturday</asp:ListItem>
<asp:ListItem>Sunday</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="startTime2" runat="server">
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="startAP2" runat="server">
<asp:ListItem>AM</asp:ListItem>
<asp:ListItem>PM</asp:ListItem>
</asp:DropDownList>
<label>- </label>
<asp:DropDownList ID="endTime2" runat="server">
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="endAP2" runat="server">
<asp:ListItem>AM</asp:ListItem>
<asp:ListItem>PM</asp:ListItem>
</asp:DropDownList>
</div>
</td>
</tr>
<tr>
<td>
<label class="col-sm-2 control-label">Timetable3:</label>
</td>
<td>
<div class="auto-style1">
<label>Every</label>
<asp:DropDownList ID="weekTime3" runat="server">
<asp:ListItem>Monday</asp:ListItem>
<asp:ListItem>Tuesday</asp:ListItem>
<asp:ListItem>Wednesday</asp:ListItem>
<asp:ListItem>Thursday</asp:ListItem>
<asp:ListItem>Friday</asp:ListItem>
<asp:ListItem>Saturday</asp:ListItem>
<asp:ListItem>Sunday</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="startTime3" runat="server">
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="startAP3" runat="server">
<asp:ListItem>AM</asp:ListItem>
<asp:ListItem>PM</asp:ListItem>
</asp:DropDownList>
<label>- </label>
<asp:DropDownList ID="endTime3" runat="server">
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="endAP3" runat="server">
<asp:ListItem>AM</asp:ListItem>
<asp:ListItem>PM</asp:ListItem>
</asp:DropDownList>
</div>
</td>
</tr>
<tr>
<td>
<label class="col-sm-2 control-label">Timetable4:</label>
</td>
<td>
<div class="auto-style1">
<label>Every</label>
<asp:DropDownList ID="weekTime4" runat="server">
<asp:ListItem>Monday</asp:ListItem>
<asp:ListItem>Tuesday</asp:ListItem>
<asp:ListItem>Wednesday</asp:ListItem>
<asp:ListItem>Thursday</asp:ListItem>
<asp:ListItem>Friday</asp:ListItem>
<asp:ListItem>Saturday</asp:ListItem>
<asp:ListItem>Sunday</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="startTime4" runat="server">
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="startAP4" runat="server">
<asp:ListItem>AM</asp:ListItem>
<asp:ListItem>PM</asp:ListItem>
</asp:DropDownList>
<label>- </label>
<asp:DropDownList ID="endTime4" runat="server">
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="endAP4" runat="server">
<asp:ListItem>AM</asp:ListItem>
<asp:ListItem>PM</asp:ListItem>
</asp:DropDownList>
<asp:CustomValidator ID="repeatTimeValidation" runat="server" ErrorMessage="Repeated Time Found." ForeColor="Red" Display="Dynamic" OnServerValidate="repeatTimeValidation_ServerValidate"></asp:CustomValidator>
</div>
</td>
</tr>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Helpers;
namespace Bracelet
{
public partial class manViewProduct1 : System.Web.UI.Page
{
BraceletDataContext bc = new BraceletDataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string id = Request.QueryString["Id"];
Product p = bc.Products.SingleOrDefault(x => x.ProductID == id);
if (p != null)
{
txtProdID.Value = p.ProductID;
txtID.Text = p.ProductID;
imgProduct.ImageUrl = "Photos/" + p.Image;
txtViewCategory.Text = p.Category.CategoryName;
txtViewCurrent.Text = p.CurrentStock.ToString();
txtViewDescription.Text = p.Description;
txtViewName.Text = p.ProductName;
txtViewUnitPrice.Text = p.UnitPrice.ToString("0.00");
imgProd.ImageUrl = "Photos/" + p.Image;
txtName.Text = p.ProductName;
txtDescription.Text = p.Description;
txtPrice.Text = p.UnitPrice.ToString("0.00");
txtLeft.Text = p.CurrentStock.ToString();
startTime.Value = p.Start;
endTime.Value = p.End;
start1.Text = p.Start;
end1.Text = p.End;
}
var timeList = bc.TimeTables.OrderByDescending(x => x.Id).Where(x => x.ProductID.Contains(id)).ToList();
txtTime1.Text = timeList[0].Time.ToString();
txtTime2.Text = timeList[1].Time.ToString();
txtTime3.Text = timeList[2].Time.ToString();
txtTime4.Text = timeList[3].Time.ToString();
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string id = Request.QueryString["Id"];
Product p = bc.Products.SingleOrDefault(x => x.ProductID == id);
if (p != null)
{
p.ProductStatus = 0;
bc.SubmitChanges();
}
Response.Redirect("manListProduct.aspx");
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Server.Transfer("manListProduct.aspx");
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string id = Request.QueryString["Id"];
float price = float.Parse(txtPrice.Text);
string name = txtName.Text;
string description = txtDescription.Text;
string productName = txtName.Text;
string productDescription = txtDescription.Text;
string wTime1 = weekTime1.Text;
string sTime1 = startTime1.Text;
string sAP1 = startAP1.Text;
string eTime1 = endTime1.Text;
string eAP1 = endAP1.Text;
string wTime2 = weekTime2.Text;
string sTime2 = startTime2.Text;
string sAP2 = startAP2.Text;
string eTime2 = endTime2.Text;
string eAP2 = endAP2.Text;
string wTime3 = weekTime3.Text;
string sTime3 = startTime3.Text;
string sAP3 = startAP3.Text;
string eTime3 = endTime3.Text;
string eAP3 = endAP3.Text;
string wTime4 = weekTime4.Text;
string sTime4 = startTime4.Text;
string sAP4 = startAP4.Text;
string eTime4 = endTime4.Text;
string eAP4 = endAP4.Text;
string start1 = startTime.Value;
string end1 = endTime.Value;
//Every Friday 5am - 6pm
string time1 = "Every " + wTime1 + " " + sTime1 + sAP1 + " - " + eTime1 + eAP1;
string time2 = "Every " + wTime2 + " " + sTime2 + sAP2 + " - " + eTime2 + eAP2;
string time3 = "Every " + wTime3 + " " + sTime3 + sAP3 + " - " + eTime3 + eAP3;
string time4 = "Every " + wTime4 + " " + sTime4 + sAP4 + " - " + eTime4 + eAP4;
List<string> timeList = new List<string>();
timeList.Add(time1);
timeList.Add(time2);
timeList.Add(time3);
timeList.Add(time4);
foreach (string t2 in timeList)
{
TimeTable tt = new TimeTable
{
ProductID = id,
Time = t2,
};
bc.TimeTables.InsertOnSubmit(tt);
}
Product p = bc.Products.SingleOrDefault(x => x.ProductID == id);
if (p != null)
{
p.ProductName = name;
p.Description = description;
p.UnitPrice = price;
p.Start = start1;
p.End = end1;
bc.SubmitChanges();
}
Response.Redirect("manListProduct.aspx");
}
}
protected void btnReset_Click(object sender, EventArgs e)
{
string id = Request.QueryString["Id"];
Product p = bc.Products.SingleOrDefault(x => x.ProductID == id);
txtName.Text = p.ProductName;
txtDescription.Text = p.Description;
txtPrice.Text = p.UnitPrice.ToString("0.00");
startTime.Value = p.Start;
endTime.Value = p.End;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string id = Request.QueryString["Id"];
int stock = int.Parse(txtStock.Text);
Product p = bc.Products.SingleOrDefault(x => x.ProductID == id);
if (p != null)
{
p.CurrentStock = p.CurrentStock + stock;
bc.SubmitChanges();
}
Response.Redirect("manListProduct.aspx");
}
protected void btnUpphoto_Click(object sender, EventArgs e)
{
string id = Request.QueryString["Id"];
Response.Redirect("manUpdateProductPhoto.aspx?Id=" + id);
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
string name = args.Value;
string id = Request.QueryString["Id"];
if (bc.Products.Any(u => u.ProductID != id && u.ProductName.ToUpper() == name.ToUpper()))
{
args.IsValid = false;
}
}
protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
{
string name = args.Value;
string id = Request.QueryString["Id"];
if (bc.Products.Any(u => u.ProductID != id && u.Description.ToUpper() == name.ToUpper()))
{
args.IsValid = false;
}
}
protected void repeatTimeValidation_ServerValidate(object source, ServerValidateEventArgs args)
{
string wTime1 = weekTime1.Text;
string sTime1 = startTime1.Text;
string sAP1 = startAP1.Text;
string eTime1 = endTime1.Text;
string eAP1 = endAP1.Text;
string wTime2 = weekTime2.Text;
string sTime2 = startTime2.Text;
string sAP2 = startAP2.Text;
string eTime2 = endTime2.Text;
string eAP2 = endAP2.Text;
string wTime3 = weekTime3.Text;
string sTime3 = startTime3.Text;
string sAP3 = startAP3.Text;
string eTime3 = endTime3.Text;
string eAP3 = endAP3.Text;
string wTime4 = weekTime4.Text;
string sTime4 = startTime4.Text;
string sAP4 = startAP4.Text;
string eTime4 = endTime4.Text;
string eAP4 = endAP4.Text;
//Every Friday 5am - 6pm
string time1 = "Every " + wTime1 + " " + sTime1 + sAP1 + " - " + eTime1 + eAP1;
string time2 = "Every " + wTime2 + " " + sTime2 + sAP2 + " - " + eTime2 + eAP2;
string time3 = "Every " + wTime3 + " " + sTime3 + sAP3 + " - " + eTime3 + eAP3;
string time4 = "Every " + wTime4 + " " + sTime4 + sAP4 + " - " + eTime4 + eAP4;
Console.WriteLine(time1);
Console.WriteLine(time2);
if (String.Equals(time1, time2))
{
args.IsValid = false;
}
else if (String.Equals(time1, time3))
{
args.IsValid = false;
}
else if (String.Equals(time1, time4))
{
args.IsValid = false;
}
else if (String.Equals(time2, time3))
{
args.IsValid = false;
}
else if (String.Equals(time2, time4))
{
args.IsValid = false;
}
else if (String.Equals(time3, time4))
{
args.IsValid = false;
}
}
}
}
Your overall requirement is to split the time in the database into a single one and then get it from the database and display it on the page, right?
You can get it and then split it. I wrote a simple demo, which may help you:
Controller:
public IActionResult Index()
{
string time = "Every Monday 10 AM - 11 Am";
string[] ssize = time.Split(null);
ArrayList arlist = new ArrayList();
foreach (String s in ssize)
{
arlist.Add(s);
}
string data = (string)arlist[0];
ViewBag.data = data;
string data1 = (string)arlist[1];
ViewBag.data1 = data1;
string data2 = (string)arlist[2];
ViewBag.data2 = data2;
string data3 = (string)arlist[3];
ViewBag.data3 = data3;
string data4 = (string)arlist[4];
ViewBag.data4 = data4;
string data5 = (string)arlist[5];
ViewBag.data5 = data5;
string data6 = (string)arlist[6];
ViewBag.data6 = data6;
return View();
}
I have omitted the operation of getting the time from the database. After getting it, you can split it by space, traverse it and add it to alist, then get the data according to the subscript, and finally display it on the page.
View:
#ViewBag.data
<select><option>#ViewBag.data1</option></select>
<select><option>#ViewBag.data2</option></select>
<select><option>#ViewBag.data3</option></select>
#ViewBag.data4
<select><option>#ViewBag.data5</option></select>
<select><option>#ViewBag.data6</option></select>
Result:

How to initialize data for flagged questions and bind it to repeater in c#?

I am working on an Online Exam System. I have stucked in questions (Flagged) these are the questions which are marked by student to be attempted later. I have table named "Questionsflagged" in db. Let's suppose there is a Now I want to initialize data for first question. Here is the code behind button of reviseflagged.
aspx page
Below is the code for repeater.
<div class="col-sm-6 col-sm-pull-1">
<div class="col-sm-1 checkbox">
<label>
<asp:CheckBox ToolTip="Mark as Flagged" ID="cbFlagged"
runat="server" OnCheckedChanged="cbFlagged_CheckedChanged" />
</label>
</div>
<asp:Repeater ID="repeaterItems" runat="server">
<ItemTemplate>
<div class="form-group">
<div class="row">
<div class="col-sm-offset-2" style="text-align:justify">
<asp:Label CssClass="question" id="lblQuestionNo" runat="server">Question # <%# DataBinder.Eval(Container.DataItem, "SrNo") %></asp:Label>: <asp:Label ID="lblQuestionText" CssClass="question" runat="server"><%# DataBinder.Eval(Container.DataItem, "QuestionText") %></asp:Label>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
<br />
<div class="col-sm-offset-2">
<asp:RadioButtonList CssClass="spaced" EnableViewState="true" ViewStateMode="Enabled" ID="rblOptions" runat="server" RepeatDirection="Vertical" OnSelectedIndexChanged="rblOptions_SelectedIndexChanged">
<asp:ListItem></asp:ListItem>
<asp:ListItem></asp:ListItem>
<asp:ListItem></asp:ListItem>
<asp:ListItem></asp:ListItem>
</asp:RadioButtonList>
</div>
</div>
Get Flagged
protected void btnReviseFlagged_Click(object sender, EventArgs e)
{
if (getFlaggedQuestions().Rows.Count != 0)
{
//CurrentPageNo = int.Parse(dt.Rows[0]["Id"].ToString());
//IncrementCount = int.Parse(dt.Rows[0]["Id"].ToString());
lblCurrentPage.Visible = true;
//var first record
//NavigateRecords(dtQuestionFlagged);
isFlagged = true;
questionsFlagged = makeFlaggedData();
IncrementCount = int.Parse(questionsFlagged.Rows[0]["SrNo"].ToString());
CurrentPageNo = int.Parse(questionsFlagged.Rows[0]["SrNo"].ToString());
var questionNo = repeaterItems.FindControl("lblQuestionNo") as Label;
questionNo = new Label();
questionNo.Text = questionsFlagged.Rows[0]["SrNo"].ToString();
var questionText = repeaterItems.FindControl("lblQuestionText") as Label;
questionText = new Label();
questionText.Text = questionsFlagged.Rows[0]["QuestionText"].ToString();
//build query for flagged
var flaggedData = from qflagged in questionsFlagged.AsEnumerable()
where qflagged.Field<int>("SrNo") == int.Parse(questionNo.Text)
select new
{
SrNo = qflagged.Field<int>("SrNo"),
QuestionText = qflagged.Field<string>("QuestionText")
};
repeaterItems.DataSource = flaggedData.AsEnumerable();
repeaterItems.DataBind();
Dictionary<string, string> values = new Dictionary<string, string>();
for (int j = 3; j < 7; j++)
{
Below is the line where I got error. I have marked question no. 5 as flagged but at this line compiler shows there is no row at position 5
values.Add(questionsFlagged.Rows[IncrementCount][j].ToString(), questionsFlagged.Columns[j].ToString());
}
//var options = repeaterItemsFindControl("rblOptions") as RadioButtonList;
//options = new RadioButtonList();
rblOptions.DataSource = values;
rblOptions.DataTextField = "Key";
rblOptions.DataValueField = "Value";
rblOptions.DataBind();
lblCurrentPage.Text = CurrentPageNo.ToString();
NavigateRecords(questionsFlagged);
}
else
{
isFlagged = false;
}
}
Normal Navigation on repeater with option to pass flagged questions
public void NavigateRecords(DataTable dtFlaggedParameter)
{
PagedDataSource pds = new PagedDataSource();
//IncrementCount+=1;
//CurrentPageNo+=1;
if (getFlaggedQuestions().Rows.Count != 0)
{
getFlaggedQuestions();
cbFlagged.Checked = false;
}
if (isFlagged == true)
{
if (dtFlaggedParameter.Rows.Count > 0)
{
pds.DataSource = dtFlaggedParameter.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 1;
// Set the PagedDataSource's current page
pds.CurrentPageIndex = CurrentPageNo;
lblCurrentPage.Text = "Page No: " + (CurrentPageNo + 1).ToString() + " of "
+ pds.PageCount.ToString();
btnPrev.Enabled = !pds.IsFirstPage;
//btnNext.Enabled = !pds.IsLastPage;
btnFirst.Enabled = !pds.IsFirstPage;
btnLast.Enabled = !pds.IsLastPage;
//btnSubmit.Visible = pds.IsLastPage;
repeaterItems.DataSource = pds;
repeaterItems.DataBind();
Dictionary<string, string> values = new Dictionary<string, string>();
for (int j = 3; j < 7; j++)
{
values.Add(dtFlaggedParameter.Rows[IncrementCount]
[j].ToString(), dtFlaggedParameter.Columns[j].ToString());
}
//var options = repeaterItemsFindControl("rblOptions") as
RadioButtonList;
//options = new RadioButtonList();
rblOptions.DataSource = values;
rblOptions.DataTextField = "Key";
rblOptions.DataValueField = "Value";
rblOptions.DataBind();
}
}
else{
//same code as above but that datatable's name is dt
}

Multiple upload in c# net 4.0

After saving information from a page in c# net 4.0 I need to add some pics in multiple mode.
I can't use net 4.5.
The problem :
If I open the page with multiple upload in the browser IE 11 this works correctly, and you can select multiple pics to upload.
If I open the same page as multiple upload in a window popup on IE 11, you can't select multiple pics to upload, but only a pic.
What's the problem ?
My code below, thank you in advance.
.aspx markup (Default.aspx)
<form id="form1" runat="server">
<div>
<asp:Panel ID="upload01" runat="server" CssClass="pure-form pure-form-stacked">
<fieldset style="margin-left: 50px">
<legend style="font-weight: bold; color: Red; margin-left: 10px;">PICS</legend>
<div class="pure-g">
<div class="pure-u-1 pure-u-md-1-3">
<label for="Pics">Pics</label>
<p>
<asp:FileUpload ID="fileUpload" multiple="true" runat="server" />
</p>
<p>
<p>
<asp:Button ID="btUpload" Text="Upload Files"
OnClick="Upload_Files" runat="server" />
</p>
</p>
<p>
<asp:Label ID="lblFileList" runat="server"></asp:Label>
</p>
<p>
<asp:Label ID="lblUploadStatus" runat="server"></asp:Label>
</p>
<p>
<asp:Label ID="lblFailedStatus" runat="server"></asp:Label>
</p>
</div>
</div>
</fieldset>
</asp:Panel>
</div>
</form>
.cs code-behind
protected void btnSave_Click(object sender, ImageClickEventArgs e)
{
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open( 'Default.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'' );", true);
}
EDIT #1
protected void Upload_Files(object sender, EventArgs e)
{
if (upload01.HasFile) // CHECK IF ANY FILE HAS BEEN SELECTED.
{
int iUploadedCnt = 0;
int iFailedCnt = 0;
HttpFileCollection hfc = Request.Files;
lblFileList.Text = "Select <b>" + hfc.Count + "</b> file(s)";
if (hfc.Count <= 10) // 10 FILES RESTRICTION.
{
for (int i = 0; i <= hfc.Count - 1; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
if (!File.Exists(Server.MapPath("\\images\\") +
Path.GetFileName(hpf.FileName)))
{
DirectoryInfo objDir =
new DirectoryInfo(Server.MapPath("\\images\\"));
string sFileName = Path.GetFileName(hpf.FileName);
string sFileExt = Path.GetExtension(hpf.FileName);
// CHECK FOR DUPLICATE FILES.
FileInfo[] objFI =
objDir.GetFiles(sFileName.Replace(sFileExt, "") + ".*");
if (objFI.Length > 0)
{
// CHECK IF FILE WITH THE SAME NAME EXISTS (IGNORING THE EXTENTIONS).
foreach (FileInfo file in objFI)
{
string sFileName1 = objFI[0].Name;
string sFileExt1 = Path.GetExtension(objFI[0].Name);
if (sFileName1.Replace(sFileExt1, "") ==
sFileName.Replace(sFileExt, ""))
{
iFailedCnt += 1; // NOT ALLOWING DUPLICATE.
break;
}
}
}
else
{
// SAVE THE FILE IN A FOLDER.
hpf.SaveAs(Server.MapPath("\\images\\") +
Path.GetFileName(hpf.FileName));
iUploadedCnt += 1;
}
}
}
}
lblUploadStatus.Text = "<b>" + iUploadedCnt + "</b> file(s) Uploaded.";
lblFailedStatus.Text = "<b>" + iFailedCnt +
"</b> duplicate file(s) could not be uploaded.";
}
else lblUploadStatus.Text = "Max. 10 files allowed.";
}
else lblUploadStatus.Text = "No files selected.";
}
I think your approach is wrong for this problem
Please see this, I hope this help.
Click here

Having trouble with paging in asp repeater

I have this aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SearchCustomer.aspx.cs" Inherits="WebApplication1.eyeofheaven.SearchCustomer" %>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta name="viewport" content="width = device-width, initial-scale = 1.0, minimum-scale = 1.0, maximum-scale = 1.0, user-scalable = no" />
<!-- Stylesheets -->
<link rel="stylesheet" type="text/css" href="StyleSheets/SearchCustomerStyle.css">
<link rel="stylesheet" href="Plugins/bootstrap-3.3.4-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Pagination Script -->
<!--Customer Script-->
<script src="JavaScripts/SearchCustomerJavascript.js"></script>
<title>Search Customer</title>
</head>
<body>
<div class="container">
<div class="row">
<form id="Form1" class="form1" runat="server">
<div class="row">
<div class="twelve columns">
<!-- Header-->
<div class="container">
<nav role="navigation" class="navbar navbar-inverse navbar-fixed-top">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Collection of nav links, forms, and other content for toggling -->
<div id="navbarCollapse" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li>Home</li>
<li class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle active" href="#">Search<b class="caret"></b></a>
<ul role="menu" class="dropdown-menu">
<li>Search Form(Customer)</li>
<li>Search Form(Vehicle)</li>
</ul>
</li>
</ul>
</div>
</nav>
</div>
</div>
</div>
<!-- Search form customer-->
<div id="searchcustomer" class="page-header">
<h3><span class="glyphicon glyphicon-th-large"></span>Search Customer</h3>
</div>
<div class="row">
<div class="col-md-4">
<input type="text" runat="server" id="search" size="20" class="form-control" placeholder="Customer ID">
</div>
<div class="col-md-4">
<select class="form-control" runat="server" id="Country">
<option value="select" selected disabled>Search by Country</option>
<option value="A:C ESTUDIO">A:C ESTUDIO</option>
<option value="Aaron McEwen-194712">Aaron McEwen-194712</option>
<option value="Accra">Accra</option>
<option value="Adoany">Adoany</option>
<option value="Aduanas">Aduanas</option>
<option value="Alex Sanchez-259029">Alex Sanchez-259029</option>
<option value="ALG Consulting-288078">ALG Consulting-288078</option>
<option value="Algeria">Algeria</option>
<option value="Algimantas Ramaskevicius">Algimantas Ramaskevicius</option>
<option value="Allan Demeritte-233953">Allan Demeritte-233953</option>
<option value="Althea Gibson-223990">Althea Gibson-223990</option>
<option value="Alvaro Delgado-279974">Alvaro Delgado-279974</option>
<option value="Amber Williamsen-212332">Amber Williamsen-212332</option>
<option value="Amos Peters-217784">Amos Peters-217784</option>
<option value="andersongordon-234453">andersongordon-234453</option>
<option value="Andrey Bolshakov-189544">Andrey Bolshakov-189544</option>
<option value="Angela green-220269">Angela green-220269</option>
<option value="ANGELMILLER-179184">ANGELMILLER-179184</option>
<option value="Angola">Angola</option>
<option value="Anguilla">Anguilla</option>
<option value="Anthony Knight-235064">Anthony Knight-235064</option>
<option value="Antigua and Barbuda">Antigua and Barbuda</option>
</select>
</div>
<div class="col-md-4">
<select class="form-control" runat="server" id="Currency">
<option value="selected" selected disabled>Search by Currency</option>
<option value="AUD">AUD (Australian Dollar)</option>
<option value="EUR">EUR (Euro)</option>
<option value="GBP">GBP (United Kingdom Pounds)</option>
<option value="JPY">JPY (Japan Yen)</option>
<option value="NZD">NZD (New Zealand Dollar)</option>
<option value="USD">USD (United States Dollar)</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-4">
<button type="button" runat="server" onserverclick="Button1_Click" id="searchinfo" class="btn btn-primary"><span class="glyphicon glyphicon-search"></span>Search Info</button>
<button type="button" runat="server" onserverclick="Button2_Click" id="Button2" class="btn btn-danger"><span class="glyphicon glyphicon-repeat"></span>Reset</button>
</div>
</div>
<hr style="border-top: dotted 1px;" />
<!-- Information Table-->
<div class="row">
<asp:Repeater runat="server" ID="repeater">
<ItemTemplate>
<div class="col-md-8">
<div id="panelmain" class="panel panel-default">
<div id="panel-heading" class="panel-heading">
<h3 id="name" align="center" class="panel-title"><%# String.Format("{0} {1}", DataBinder.Eval(Container.DataItem, "Firstname").ToString(), DataBinder.Eval(Container.DataItem, "Lastname").ToString()) %></h3>
</div>
<div id="panelbody" class="panel-body">
<ul class="list-unstyled">
<li>
<span class="spanlist">IDCustomer : </span><%# DataBinder.Eval(Container.DataItem, "IDCustomer").ToString() %>
</li>
<li>
<span class="spanlist">IDAccountManager : </span><%# DataBinder.Eval(Container.DataItem, "IDAccountManager").ToString() %>
</li>
<li>
<span class="spanlist">IDBillingAddress : </span><%# DataBinder.Eval(Container.DataItem, "IDBillingAddress").ToString() %>
</li>
<li>
<span class="spanlist">IDCountry : </span><%# DataBinder.Eval(Container.DataItem, "IDCountry").ToString() %>
</li>
<li>
<span class="spanlist">IDCredit : </span><%# DataBinder.Eval(Container.DataItem, "IDCredit").ToString() %>
</li>
<li>
<span class="spanlist">IDFrequency : </span><%# DataBinder.Eval(Container.DataItem, "IDFrequency").ToString() %>
</li>
<li>
<span class="spanlist">IDOwner : </span><%# DataBinder.Eval(Container.DataItem, "IDOwner").ToString() %>
</li>
<li>
<span class="spanlist">IDPort : </span><%# DataBinder.Eval(Container.DataItem, "IDPort").ToString() %>
</li>
<li>
<span class="spanlist">IDSite : </span><%# DataBinder.Eval(Container.DataItem, "IDSite").ToString() %>
</li>
<li>
<span class="spanlist">IDRecipient : </span><%# DataBinder.Eval(Container.DataItem, "IDRecipient").ToString() %>
</li>
<li>
<span class="spanlist">AccessType : </span><%# DataBinder.Eval(Container.DataItem, "AccessType").ToString() %>
</li>
<li>
<span class="spanlist">Active : </span><%# DataBinder.Eval(Container.DataItem, "Active").ToString() %>
</li>
</ul>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div>
<asp:LinkButton ID="linkPrevious" runat="server" NavigateUrl="~/SearchCustomer.aspx" Font-Bold="true" OnClick="linkPrevious_Click">Prev Page</asp:LinkButton>
<asp:LinkButton ID="linkNext" runat="server" NavigateUrl="~/SearchCustomer.aspx" Font-Bold="true" OnClick="linkNext_Click">Next Page</asp:LinkButton>
</div>
</form>
</body>
</html>
and its aspx code behind:
using MSSQLConnector;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services.Description;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1.eyeofheaven
{
public partial class SearchCustomer : System.Web.UI.Page
{
public static string query = null;
private int cnt;
private DataSet selectedData;
private DataTable dt;
private MSConnector connector = new MSConnector();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Function for BindRepeater
BindRepeater();
}
protected void Button2_Click(object sender, EventArgs e)
{
this.repeater.Visible = false;
this.search.Value = "";
this.Country.Value = "select";
this.Currency.Value = "selected";
}
//This property will contain the current page number
public int PageNumber
{
get
{
if (ViewState["PageNumber"] != null)
{
return Convert.ToInt32(ViewState["PageNumber"]);
}
else
{
return 0;
}
}
set { ViewState["PageNumber"] = value; }
}
//Asp:ListView
private void BindRepeater()
{
//ConnectionString for accessing into MSSql
connector.ConnectionString = "SERVER=xbetasql,52292;UID=username;Password=secret;DATABASE=ATDBSQL;";
//Get the values from id's
string customer = (this.search.Value);
string country = (this.Country.Value);
string idcurrency = (this.Currency.Value);
//Conditions for query
if (country != "select")
{
if (idcurrency != "selected")
{
query = "select * from customer where country = '" + country + "' and idcurrency = '" + idcurrency + "'";
}
else
{
query = "select * from customer where country = '" + country + "'";
}
}
else if (idcurrency != "selected")
{
query = "select * from customer where idcurrency = '" + idcurrency + "'";
}
else if ((this.search.Value) == customer)
{
query = "select * from customer where idcustomer = '" + customer + "'";
}
else if (customer == "")
{
Response.Write("<script>alert('No Id Inputted, Data Not Found.')</script>");
}
//DataSet and DataTable (get the data and display it into asp:repeater
selectedData = connector.ExecuteQuery(query);
dt = selectedData.Tables[0];
//Set PageData Settings
PagedDataSource pagedData = new PagedDataSource();
pagedData.DataSource = dt.DefaultView;
pagedData.AllowPaging = true;
pagedData.PageSize = 3;
pagedData.CurrentPageIndex = PageNumber;
int vcnt = cnt / pagedData.PageSize;
if (PageNumber < 1)
{
linkPrevious.Visible = false;
}
else if (PageNumber > 0)
{
linkPrevious.Visible = true;
}
if (PageNumber == vcnt)
{
linkNext.Visible = false;
}
else if(PageNumber < vcnt)
{
linkNext.Visible = true;
}
//Binding the repeater
repeater.Visible = true;
repeater.DataSource = pagedData;
repeater.DataBind();
//Binding the repeater
}
protected void linkNext_Click(object sender, EventArgs e)
{
PageNumber += 1;
BindRepeater();
}
protected void linkPrevious_Click(object sender, EventArgs e)
{
PageNumber -= 1;
BindRepeater();
}
}
}
My asp:LinkButton, does not work for paging in my repeater when I first open my web page the asp:linkbutton is there, but when searched and display all the data from my page the linkbutton is gone although it display data that I searched for. But the problem is pagination doesn't seem to work. What seems to be the problem for my code? Here's the link as a reference for my code.
I'm new to c# programming(webform) and I have few knowledge about pagination in c#.
It's because of
int vcnt = cnt / pagedData.PageSize;
'cnt' you haven't set, So its always zero that's why 'vcnt' will zero.
that's why your link will visible false always after you search things.
So Solution is
int vcnt = dt.DefaultView.Count / pagedData.PageSize;
Hope this will solve your problem
Happy Coding :)
I got it right :)
here's the code for pagination:
using MSSQLConnector;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services.Description;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1.eyeofheaven
{
public partial class SearchCustomer : System.Web.UI.Page
{
public static string query = null;
private int cnt;
private DataSet selectedData;
private DataTable dt;
private MSConnector connector = new MSConnector();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Function for BindRepeater
BindRepeater();
}
protected void Button2_Click(object sender, EventArgs e)
{
this.repeater.Visible = false;
this.linkPrevious.Visible = false;
this.linkNext.Visible = false;
this.search.Value = "";
this.Country.Value = "select";
this.Currency.Value = "selected";
}
//This property will contain the current page number
public int PageNumber
{
get
{
if (ViewState["PageNumber"] != null)
{
return Convert.ToInt32(ViewState["PageNumber"]);
}
else
{
return 0;
}
}
set { ViewState["PageNumber"] = value; }
}
//Asp:ListView
private void BindRepeater()
{
//ConnectionString for accessing into MSSql
connector.ConnectionString = "SERVER=xbetasql,52292;UID=username;Password=secret;DATABASE=ATDBSQL;";
//Get the values from id's
string customer = (this.search.Value);
string country = (this.Country.Value);
string idcurrency = (this.Currency.Value);
//Conditions for query
if (customer != "")
{
query = "select * from customer where idcustomer = '" + customer + "'";
}
else if (country != "select")
{
if (idcurrency != "selected")
{
query = "select * from customer where country = '" + country + "' and idcurrency = '" + idcurrency + "'";
}
else
{
query = "select * from customer where country = '" + country + "'";
}
}
else if (idcurrency != "selected")
{
query = "select * from customer where idcurrency = '" + idcurrency + "'";
}
else if (customer == "")
{
Response.Write("<script>alert('No Id Inputted, Data Not Found.')</script>");
}
else
{
Response.Write("<script>alert('Invalid input.')</script>");
}
//DataSet and DataTable (get the data and display it into asp:repeater
selectedData = connector.ExecuteQuery(query);
dt = selectedData.Tables[0];
//Set PageData Settings
PagedDataSource pagedData = new PagedDataSource();
pagedData.DataSource = dt.DefaultView;
pagedData.AllowPaging = true;
//Set to 2 pages to be viewed
pagedData.PageSize = 2;
pagedData.CurrentPageIndex = PageNumber;
//Count to 2 pages to appear when clicking next or previous
int vcnt = dt.DefaultView.Count / pagedData.PageSize;
if (PageNumber == 1)
{
linkPrevious.Visible = false;
}
else if (PageNumber < 1)
{
linkPrevious.Visible = false;
}
else if (PageNumber > 0)
{
linkPrevious.Visible = true;
}
if (PageNumber == vcnt)
{
linkNext.Visible = false;
}
//Hide previous and next if it is firstpage and lastpage
else if(PageNumber < vcnt)
{
linkNext.Visible = !pagedData.IsLastPage;
linkPrevious.Visible = !pagedData.IsFirstPage;
}
//Binding the repeater
if (dt.Rows.Count > 0)
{
repeater.Visible = true;
repeater.DataSource = pagedData;
repeater.DataBind();
}
else
{
Response.Write("<script>alert('No Data Found.')</script>");
}
}
protected void linkNext_Click(object sender, EventArgs e)
{
linkNext.Visible = true;
PageNumber += 1;
BindRepeater();
}
protected void linkPrevious_Click(object sender, EventArgs e)
{
linkPrevious.Visible = true;
PageNumber -= 1;
BindRepeater();
}
}
}
Hope this is a good reference among programmers. :)

Update MasterPage control from Content page

I have an UpdatePanel with a Label which I would like to update in my MasterPage. The event is taking place from my Content page and here are the codes.
Content ASP.net code:
<%# MasterType TypeName="OnBoarding.Pages.Site" %>
<asp:DropDownList ID="ddlTaskName" CssClass="chosen-select" DataSourceID="dsPopulateTaskName" AutoPostBack="true" DataValueField="Task Name" runat="server" Width="100%" Font-Size="11px" AppendDataBoundItems="true" OnSelectedIndexChanged="ddlTaskName_onSelectIndexChanged">
<asp:ListItem Text="All" Value="%"></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="dsPopulateTaskName" runat="server" ConnectionString="<%$ ConnectionStrings:gvConnString %>" SelectCommand="QUERY"></asp:SqlDataSource>
C# code-behind:
protected void ddlTaskName_onSelectIndexChanged(object sender, EventArgs e)
{
FilterMessages();
}
public void FilterMessages()
{
DataTable msgTable = HttpContext.Current.Session["MessageTable"] as DataTable;
string query = "";
Stack msgStack = new Stack();
if (ddlClient.SelectedIndex > 0)
{
query += "Client = '" + ddlClient.SelectedItem.Text + "' OR Client is NULL";
}
if (ddlSite.SelectedIndex > 0 && query == "")
{
query += "Site = '" + ddlSite.SelectedItem.Text + "' OR Site is NULL";
}
else if (ddlSite.SelectedIndex > 0)
{
query += " AND Site = '" + ddlSite.SelectedItem.Text + "' OR Site is NULL";
}
if (ddlProvider.SelectedIndex > 0 && query == "")
{
query += "Provider = '" + ddlProvider.SelectedItem.Text + "' OR Provider is NULL";
}
else if (ddlProvider.SelectedIndex > 0)
{
query += " AND Provider = '" + ddlProvider.SelectedItem.Text + "' OR Provider is NULL";
}
UpdatePanel upMsg = (UpdatePanel)Master.FindControl("upMessage");
if (query != "")
{
DataRow[] result = msgTable.Select(query);
System.Web.UI.WebControls.Label lblMsg = (System.Web.UI.WebControls.Label)Master.FindControl("lblMessage");
if (lblMsg != null)
{
lblMsg.Text = "";
}
//lblMessage.Text = "";
foreach (DataRow row in result)
{
if (row["Active"].ToString() == "True")
{
string[] myStrings = new string[] { row["Created"].ToString().Split(' ')[0], string.IsNullOrEmpty(row["Client"].ToString()) ? null : row["Client"].ToString(), string.IsNullOrEmpty(row["Site"].ToString()) ? null : row["Site"].ToString(), row["Message"].ToString() };
string strResult = string.Join(" ", myStrings.Where(str => !string.IsNullOrEmpty(str)));
msgStack.Push(strResult);
}
}
foreach (string message in msgStack)
{
lblMsg.Text += message + "</br>";
//lblMessage.Text += message + "</br>";
}
}
else
{
PopulateMessageGV();
}
if (upMsg != null)
{
upMsg.Update();
}
//upMessage.Update();
}
protected void PopulateMessageGV()
{
UpdatePanel upMsg = (UpdatePanel)Master.FindControl("upMessage");
System.Web.UI.WebControls.Label lblMsg = (System.Web.UI.WebControls.Label)Master.FindControl("lblMessage");
if (lblMsg != null)
{
lblMsg.Text = "";
}
//lblMessage.Text = "";
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Created", typeof(string));
dt.Columns.Add("Message", typeof(string));
dt.Columns.Add("Client", typeof(string));
dt.Columns.Add("Site", typeof(string));
dt.Columns.Add("Provider", typeof(string));
dt.Columns.Add("Active", typeof(bool));
dt.Columns.Add("CreatedBy", typeof(string));
using (var context = new ClientContext(hostWeb))
{
Stack msgStack = new Stack();
var hostSite = context.Web;
context.Load(hostSite, s => s.Title);
context.ExecuteQuery();
ListCollection allLists = hostSite.Lists;
Microsoft.SharePoint.Client.List messageList = allLists.GetByTitle("AdminMessage");
context.Load(messageList);
context.ExecuteQuery();
try
{
var query = CamlQuery.CreateAllItemsQuery();
Microsoft.SharePoint.Client.ListItemCollection allItems = messageList.GetItems(query);
context.Load(allItems);
context.ExecuteQuery();
if (allItems.Count > 0)
{
foreach (Microsoft.SharePoint.Client.ListItem item in allItems)
{
DataRow dr = dt.NewRow();
dr["ID"] = item["ID"];
dr["Created"] = item["Created"];
dr["Message"] = item["Message"];
dr["Client"] = item["Client"];
dr["Site"] = item["Site"];
dr["Provider"] = item["Provider"];
dr["Active"] = item["Active"];
FieldUserValue test = (FieldUserValue)item["Author"];
dr["CreatedBy"] = test.LookupValue.ToString();
dt.Rows.Add(dr);
if (item["Active"].ToString() == "True")
{
string[] myStrings = new string[] { item["Created"].ToString().Split(' ')[0], string.IsNullOrEmpty(dr["Client"].ToString()) ? null : item["Client"].ToString(), string.IsNullOrEmpty(dr["Site"].ToString()) ? null : item["Site"].ToString(), item["Message"].ToString() };
string result = string.Join(" ", myStrings.Where(str => !string.IsNullOrEmpty(str)));
msgStack.Push(result);
}
}
}
HttpContext.Current.Session["MessageTable"] = dt;
foreach (string message in msgStack)
{
lblMsg.Text += message + "</br>";
//lblMessage.Text += message + "</br>";
}
if (upMsg != null)
{
upMsg.Update();
}
//upMessage.Update();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
}
MasterPage ASP.net code:
<asp:UpdatePanel runat="server" ID="upMessage" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblMessage" Font-Size="x-small" runat="server" Text="" ClientIDMode="Static"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
When I change the DropDown option the UpdatePanel in the masterpage doesn't update although putting a breakpoint there, shows that it is being hit.
How do I resolve the issue?
Basically, you want to expose Public Property from MasterPage. Then access it from ContentPage.
Master Page
<%# Master Language="C#" AutoEventWireup="true"
CodeBehind="Site.Master.cs" Inherits="DemoWebForm.Site" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
<asp:Label runat="server" ID="MessageLabel" />
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</form>
</body>
</html>
public partial class Site : System.Web.UI.MasterPage
{
public string MessageLabelText
{
get { return MessageLabel.Text; }
set { MessageLabel.Text = value; }
}
}
Content Page
<%# Page Title="Home Page" Language="C#"
MasterPageFile="~/Site.Master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="DemoWebForm._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:DropDownList ID="TaskNameDropDownList"
runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="TaskNameDropDownList_SelectedIndexChanged">
<asp:ListItem Text="One" Value="1" />
<asp:ListItem Text="Two" Value="2" />
</asp:DropDownList>
</asp:Content>
public partial class _Default : Page
{
protected void TaskNameDropDownList_SelectedIndexChanged(
object sender, EventArgs e)
{
var master = Master as Site;
if (master != null)
{
master.MessageLabelText = TaskNameDropDownList.SelectedValue;
}
}
}

Categories

Resources