Update MasterPage control from Content page - c#

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

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
}

Javascript not working with Ext.Net

I am using Asp.net with Ext.Net framework. And I must use Javascript code (not ext.net code).
Default.aspx page:
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button runat="server" Text="tıkla" ID="btnGetir" OnClick="btnGetir_Click" />
............
............
Default.aspx.cs page:
public void btnGetir_Click(object sender, EventArgs e)
{
String url = "http://blablablablabla:8080/MeramElektrik2/webresources/entities.layers/GetLayer/1004";
String html_sonuc;
WebResponse objResponse;
WebRequest objRequest = HttpWebRequest.Create(url);
objResponse = objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
html_sonuc = sr.ReadToEnd();
sr.Close();
}
////////////Script Çalıştırma Kodu///////////////////////////
ScriptManager.RegisterStartupScript(
this,
this.GetType(),
"deneme2",
"deserialize('" + html_sonuc + "');",
true);
/////////////////////////////////////////////////////////////
txtScript.Text = html_sonuc;
}
OpenLayerUsers.js page:
function deserialize(html_sonuc) { //GEOJSON I, ÇİZİLMİŞ ŞEKLE DÖNÜŞTÜRÜYOR
//var element = document.getElementById('txtScript');
var features = geojson.read(html_sonuc);
//var features = json.read(element.value);
var bounds;
if (features) {
if (features.constructor != Array) {
features = [features];
}
for (var i = 0; i < features.length; ++i) {
if (!bounds) {
bounds = features[i].geometry.getBounds();
} else {
bounds.extend(features[i].geometry.getBounds());
}
}
vectors.addFeatures(features);
map.zoomToExtent(bounds);
var plural = (features.length > 1) ? 's' : '';
//element.value = features.length + ' feature' + plural + ' added'
} else {
//element.value = 'Bad input';
}
}
Result, deserialize(html_sonuc) function not working.
here is the simple test case
aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Js/jquery-1.8.2.min.js"></script>
<script>
Ext.onReady(function () {
});
function deserialize(testdt) {
alert('sonic bumm:' + testdt);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<ext:ResourceManager ID="myrsc" runat="server"></ext:ResourceManager>
<div>
<asp:Button runat="server" Text="tıkla" ID="btnGetir" OnClick="btnGetir_Click" />
</div>
</form>
</body>
</html>
and the code behind;
protected void btnGetir_Click(object sender, EventArgs e)
{
// do something here
// and add the client script
string testdt = "testdata";
string script = "deserialize('" + testdt + "')";
myrsc.AddScript(script);
}

How to create multipe column on ajax auto complete?

I create a table for searching items on ajax auto complete, I want to design like that(Table-1):
There is my web service code:
[WebMethod]
public object[] GetResult(string prefixText, int count)
{
List<object> result;
result = new List<object>();
try
{
Some Database query...
while (rd.Read())
{
result.Add(new
{
ProductName = rd[0],
Pic= rd[1],
RecID = rd[2],
Properties= rd[3]
});
}
rd.Close();
con.Close();
}
catch (Exception ex)
{
}
return result.ToArray();
}
I add a List object for all data and its java script side:
<script type="text/javascript">
function onPopulated() {
var list = $find("ace").get_completionList();
var count = list.childNodes.length;
for (i = 0; i < count; i++) {
var item = list.childNodes[i]._value;
var name = item.ProductName ;
var kategory = item.Properties;
var RecID = item.RecID;
var Pic= item.Pic;
var url = "http://abc.com.tr/img/p_" + RecID + "_" + Pic+ "_01.jpg"
list.childNodes[i].innerHTML = '<span id="name"><table><tr style="width:260px;height:55px;" ><td><img width="50" height="50" style="position:relative;" src="' + url + '"/></td><td style="font-size:11px;font-weight:bold;min-height:20px;">'+ name + '</td></tr></table></span>';
//'<span id="name"><table style="width:260px;"><tr><td><img width="50" height="50" src="' + url + '"/></td><td><b style="font-size:12px;">' + name + '</b><br>' + kategory + '</td></tr></table></span>'
}
}
function onSelected() {
var i = $find("ace")._selectIndex;
var item = list.get_completionList().childNodes[i]._value;
$get("txtSearch").value = item.name;
}
</script>
i add a table it view like that(Table-2):
and finally its my ajax toolkit tag:
<asp:TextBox runat="server" ID="txtSearch" Width="261" />
<cc1:AutoCompleteExtender ID="txtSearch_AutoCompleteExtender" runat="server"
DelimiterCharacters="" Enabled="True" ServicePath="WebService.asmx"
FirstRowSelected="true"
EnableCaching="false"
ServiceMethod="GetResult"
MinimumPrefixLength="1"
CompletionListCssClass="completionList"
CompletionListHighlightedItemCssClass="itemHighlighted"
CompletionListItemCssClass="listItem"
OnClientItemSelected="onSelected" OnClientPopulated="onPopulated"
BehaviorID="ace" TargetControlID="txtSearch">
</cc1:AutoCompleteExtender>
How to create table like table-1? Please help me Thanks for your answers
I think, the following link may help you : http://vincexu.blogspot.com/2009/01/custom-autocomplete-6-multicolumn.html
For the record pasting code from the above mentioned article.
ASPX
<head runat="server">
<title></title>
<link href="../Default.css" rel="stylesheet" type="text/css" />
<style>
.cloumnspan
{
width:35px;
padding:0px;
border-color:Black;
border-style:solid;
border-width:1px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager runat="server" ID="ScriptManager1" />
<asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
<ajaxToolkit:AutoCompleteExtender
runat="server" OnClientPopulated="dd" OnClientItemSelected="itemSelected"
BehaviorID="AutoCompleteEx"
ID="autoComplete1"
TargetControlID="myTextBox"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList5"
MinimumPrefixLength="2"
CompletionInterval="1000"
EnableCaching="true"
CompletionSetCount="8"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
DelimiterCharacters=";, :">
</ajaxToolkit:AutoCompleteExtender>
</form>
<script type="text/javascript">
function itemSelected(ev)
{
var index=$find("AutoCompleteEx")._selectIndex;
var value=$find("AutoCompleteEx").get_completionList().childNodes[index]._value;
$find("AutoCompleteEx").get_element().value = value;
}
function dd()
{
var comletionList=$find("AutoCompleteEx").get_completionList();
for(i=0;i<comletionList.childNodes.length;i++) {
var itemobj=new Object();
var _data = comletionList.childNodes[i]._value;
itemobj.name= _data.substring(_data.lastIndexOf('|') + 1); // parse name as item value
comletionList.childNodes[i]._value = itemobj.name;
_data = _data.substring(0, _data.lastIndexOf('|'));
itemobj.age = _data.substring(_data.lastIndexOf('|') + 1);
_data = _data.substring(0, _data.lastIndexOf('|'));
itemobj.id = _data.substring(_data.lastIndexOf('|') + 1);
comletionList.childNodes[i].innerHTML = "<div class='cloumnspan' style='width:10%;float:left'>" + itemobj.id + "</div>"
+ "<div class='cloumnspan' style='width:70%;float:left'>" + itemobj.name + "</div>"
+ "<div class='cloumnspan' style='width:18%;'>" + itemobj.age + "</div>";
}
}
</script>
</body>
Web Method:
[WebMethod]
public string[] GetCompletionList5(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}
if (prefixText.Equals("xyz"))
{
return new string[0];
}
Random random = new Random();
List<string> items = new List<string>(count);
for (int i = 0; i < count; i++)
{
char c1 = (char)random.Next(65, 90);
char c2 = (char)random.Next(97, 122);
char c3 = (char)random.Next(97, 122);
int id = i;
int age = random.Next(18, 70);
items.Add(id.ToString() + "|" + age.ToString() + "|" + prefixText + c1 + c2 + c3);
}
return items.ToArray();
}

Sitecore Feed latest 2 items

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

Categories

Resources