I have a dhtmlgoodies_calendar in my asp.net application and have made some changes to the writeCalendarContent method to disable the dates in the past. It works fine on Internet explorer. But in firefox and chrome the dates in the past are still displayed anyways.
Does anybody have any idea in how to make this work in those browers?
any help is appreciated.
Thanks
Here is my method:
function writeCalendarContent()
{
var blockDateInPast = true;
var calendarContentDivExists = true;
if(!calendarContentDiv){
calendarContentDiv = document.createElement('DIV');
calendarDiv.appendChild(calendarContentDiv);
calendarContentDivExists = false;
}
currentMonth = currentMonth/1;
var d = new Date();
var data = new Date();
var AnoAtual = data.getYear();
var MesAtual = data.getMonth();
var DiaAtual = data.getDate();
d.setFullYear(currentYear);
d.setDate(1);
d.setMonth(currentMonth);
var dayStartOfMonth = d.getDay();
if (! weekStartsOnSunday) {
if(dayStartOfMonth==0)dayStartOfMonth=7;
dayStartOfMonth--;
}
document.getElementById('calendar_year_txt').innerHTML = currentYear;
document.getElementById('calendar_month_txt').innerHTML = monthArray[currentMonth];
document.getElementById('calendar_hour_txt').innerHTML = currentHour;
document.getElementById('calendar_minute_txt').innerHTML = currentMinute;
var existingTable = calendarContentDiv.getElementsByTagName('TABLE');
if(existingTable.length>0){
calendarContentDiv.removeChild(existingTable[0]);
}
var calTable = document.createElement('TABLE');
calTable.width = '100%';
calTable.cellSpacing = '0';
calendarContentDiv.appendChild(calTable);
var calTBody = document.createElement('TBODY');
calTable.appendChild(calTBody);
var row = calTBody.insertRow(-1);
row.className = 'calendar_week_row';
if (showWeekNumber) {
var cell = row.insertCell(-1);
cell.innerHTML = weekString;
cell.className = 'calendar_week_column';
cell.style.backgroundColor = selectBoxRolloverBgColor;
}
for(var no=0;no<dayArray.length;no++){
var cell = row.insertCell(-1);
cell.innerHTML = dayArray[no];
}
var row = calTBody.insertRow(-1);
if (showWeekNumber) {
var cell = row.insertCell(-1);
cell.className = 'calendar_week_column';
cell.style.backgroundColor = selectBoxRolloverBgColor;
var week = getWeek(currentYear,currentMonth,1);
cell.innerHTML = week; // Week
}
for(var no=0;no<dayStartOfMonth;no++){
var cell = row.insertCell(-1);
cell.innerHTML = ' ';
}
var colCounter = dayStartOfMonth;
var daysInMonth = daysInMonthArray[currentMonth];
if(daysInMonth==28){
if(isLeapYear(currentYear))daysInMonth=29;
}
for(var no=1;no<=daysInMonth;no++){
d.setDate(no-1);
if(colCounter>0 && colCounter%7==0){
var row = calTBody.insertRow(-1);
if (showWeekNumber) {
var cell = row.insertCell(-1);
cell.className = 'calendar_week_column';
var week = getWeek(currentYear,currentMonth,no);
cell.innerHTML = week; // Week
cell.style.backgroundColor = selectBoxRolloverBgColor;
}
}
var cell = row.insertCell(-1);
if (currentYear<AnoAtual && blockDateInPast==true)
{
cell.className='DesactiveDay';
cell.onclick = null;
}
else if (currentYear==AnoAtual)
{
if (currentMonth < MesAtual && blockDateInPast == true)
{
cell.className='DesactiveDay';
cell.onclick = null;
}
else if (currentMonth==MesAtual)
{
if (no < DiaAtual && blockDateInPast == true)
{
cell.className='DesactiveDay';
cell.onclick = null;
}
else
{
cell.onclick = pickDate;
}
}
else
{
cell.onclick = pickDate;
}
}
else
{
cell.onclick = pickDate;
}
if (cell.onclick == pickDate)
{
if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
cell.className='activeDay';
cell.onclick = pickDate;
}
}
cell.innerHTML = no;
colCounter++;
}
if(!document.all){
if(calendarContentDiv.offsetHeight)
document.getElementById('topBar').style.top = calendarContentDiv.offsetHeight + document.getElementById('timeBar').offsetHeight + document.getElementById('topBar').offsetHeight -1 + 'px';
else{
document.getElementById('topBar').style.top = '';
document.getElementById('topBar').style.bottom = '0px';
}
}
if(iframeObj){
if(!calendarContentDivExists)setTimeout('resizeIframe()',350);else setTimeout('resizeIframe()',10);
}
}
Just add following code at the end of writeCalendarContent(),
if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
cell.className='activeDay';
cell.onclick = pickDate;
}
else if(currentYear<inputYear || currentMonth < inputMonth || no<inputDay){
cell.className = 'inactive-date';
}
else{
cell.onclick = pickDate;
}
cell.innerHTML = no;
colCounter++;
It adds the click event only for current date and next dates. It doesn't add click for past dates. You can add style for past dates(add style for inactive-date class).
Not at all, this following code is correct and tested
if(disabledDateInPast){
var now = new Date();
var yearOfNow = now.getFullYear();
var monthOfNow = now.getMonth();
var noOfNow = now.getDate();
if(currentYear < yearOfNow){
cell.className = 'desactiveDay';
}
else if(currentYear > yearOfNow){
cell.onclick = pickDate;
}
else if (currentYear == yearOfNow){
if(currentMonth < monthOfNow){
cell.className = 'desactiveDay';
}
else if(currentMonth > monthOfNow){
cell.onclick = pickDate;
}
else if(currentMonth == monthOfNow){
if(no < noOfNow){
cell.className = 'desactiveDay';
}
else{
cell.onclick = pickDate;
}
}
}
}
else{
cell.onclick = pickDate;
}
if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
cell.className='activeDay';
}
Related
I have a search query which search for all jobs in the database and than displays them in accordance to the most recent ones filtering the data by date as follows:
result = db.AllJobModel.Where(a => a.JobTitle.Contains(searchTitle) && a.locationName.Contains(searchLocation)).ToList());
result = (from app in result orderby DateTime.ParseExact(app.PostedDate, "dd/MM/yyyy", null) descending select app).ToList();
result = GetAllJobModelsOrder(result);
after that I have a method GetAllJobModelsOrder which displays jobs in order which seems to be work fine but in my case its not ordering jobs so I need to understand where I am wrong:
private List<AllJobModel> GetAllJobModelsOrder(List<AllJobModel> result)
{
var list = result.OrderBy(m => m.JobImage.Contains("job1") ? 1 :
m.JobImage.Contains("job2") ? 2 :
m.JobImage.Contains("job3") ? 3 :
m.JobImage.Contains("job4") ? 4 :
m.JobImage.Contains("job5") ? 5 :
6)
.ToList();
return list;
}
The result I get is about 10 jobs from job1 and than followed by other jobs in the same order what I would like to achieve is to filter the most recent jobs than display one job from each type of a job.
An example of the input would be as follows:
AllJobModel allJobModel = new AllJobModel
{
JobDescription = "Description",
JobImage = "Job1",
JobTitle = "title",
locationName = "UK",
datePosted = "15/06/2020",
}
The output that I get is as follows:
In where result should be mixed from different jobs.
Excepted resulta as follows a specific order of job source--1. TotalJob[0] :: 2. MonsterJob[0] :: 3. Redd[0] :: 4. TotalJob[ 1 ] :: 5. MonsterJob[ 1 ] ::6. Redd[ 1 ]:
I have tried the following solution but list data structure seems to be not stroing data in order:
private List<AllJobModel> GetAllJobModelsOrder(List<AllJobModel> result)
{
string lastItem = "";
List<AllJobModel> list = new List<AllJobModel>();
int pos = -1;
while(result.Count != 0)
{
for(int i = 0; i < result.Count; i++)
{
if(result[i].JobImage.Contains("reed") && (lastItem == "" || lastItem == "total" || lastItem == "monster"))
{
pos++;
list.Insert(pos,result[i]);
lastItem = "reed";
result.Remove(result[i]);
break;
}else if (result[i].JobImage.Contains("total") && (lastItem == "reed" || lastItem == "monster" || lastItem == "" ))
{
pos++;
list.Insert(pos, result[i]);
lastItem = "total";
result.Remove(result[i]);
break;
}else if(result[i].JobImage.Contains("monster.png") && (lastItem =="total" || lastItem == "reed" || lastItem == "" ))
{
pos++;
list.Insert(pos, result[i]);
lastItem = "monster";
result.Remove(result[i]);
break;
}else if(result[i].JobImage.Contains("reed") &&( lastItem == "reed"))
{
if(result.FirstOrDefault(a=>a.JobImage.Contains("total") || a.JobImage.Contains("monster")) != null)
{
lastItem = "total";
break;
}
else
{
pos++;
list.Insert(pos, result[i]);
lastItem = "reed";
result.Remove(result[i]);
break;
}
}
else if (result[i].JobImage.Contains("total") && (lastItem == "total"))
{
if (result.FirstOrDefault(a => a.JobImage.Contains("reed") || a.JobImage.Contains("monster")) != null)
{
lastItem = "monster";
break;
}
else
{
pos++;
list.Insert(pos, result[i]);
lastItem = "total";
result.Remove(result[i]);
break;
}
}
else if (result[i].JobImage.Contains("monster") && (lastItem == "monster"))
{
if (result.FirstOrDefault(a => a.JobImage.Contains("total") || a.JobImage.Contains("reed")) != null)
{
lastItem = "reed";
break;
}
else
{
pos++;
list.Insert(pos, result[i]);
lastItem = "monster";
result.Remove(result[i]);
break;
}
}
}
}
return list;
}
also what I found is that the value of the elements in the list is different from what its actual value. So I am not sure if this is an error with my code or with visual studio:
you can use the below concept here. I am sorting a list based on the numeric value at the end of each string value using Regex.
List<string> ls = new List<string>() { "job2", "job1", "job4", "job3" };
ls = ls.OrderBy(x => Regex.Match(x, #"\d+$").Value).ToList();
Certainly the requirement was not as straight forward as initially thought. Which is why I am offering a second solution.
Having order by and rotate the offering "Firm" in a type of priority list for a set number of times and then just display whatever comes after that requires a custom solution. If the one algorithm you have works and you are happy then great. Otherwise, I have come up with this algorithm.
private static List<AllJobModel> ProcessJobs(List<AllJobModel> l)
{
var noPriorityFirst = 2;
var orderedList = new List<AllJobModel>();
var priorityImage = new string[] { "TotalJob", "MonsterJob", "Redd" };
var gl = l.OrderBy(o => o.datePosted).GroupBy(g => g.datePosted).ToList();
foreach (var g in gl)
{
var key = g.Key;
for (int i = 0; i < noPriorityFirst; i++)
{
foreach (var j in priorityImage)
{
var a = l.Where(w => w.datePosted.Equals(key) && w.JobImage.Equals(j)).FirstOrDefault();
if (a != null)
{
orderedList.Add(a);
var ra = l.Remove(a);
}
}
}
foreach (var j in l.ToList())
{
var a = l.Where(w => w.datePosted.Equals(key)).FirstOrDefault();
if (a != null)
{
orderedList.Add(a);
var ra = l.Remove(a);
}
}
}
return orderedList;
}
To test this process I have created this Console app:
static void Main(string[] args)
{
Console.WriteLine("Start");
var l = CreateTestList();
var lJobs = ProcessJobs(l);
lJobs.ForEach(x => Console.WriteLine($"{x.datePosted} : {x.JobImage}"));
}
private static List<AllJobModel> CreateTestList()
{
var orderedList = new List<AllJobModel>();
var l = new List<AllJobModel>();
var priorityImage = new string[] { "TotalJob", "MonsterJob", "Redd" };
var rand = new Random();
var startTime = DateTime.Now;
for (int i = 0; i < 20; i++)
{
var j = rand.Next(0, priorityImage.Length);
var h = rand.Next(0, 4);
var a = new AllJobModel();
a.JobDescription = "Desc " + i;
a.JobImage = priorityImage[j];
a.JobTitle = "Title" + i;
a.locationName = "UK";
a.datePosted = startTime.AddDays(h);
l.Add(a);
}
for (int i = 0; i < 20; i++)
{
var j = rand.Next(0, priorityImage.Length);
var h = rand.Next(0, 4);
var a = new AllJobModel();
a.JobDescription = "Desc " + i;
a.JobImage = "Job " + i;
a.JobTitle = "Title" + i;
a.locationName = "UK";
a.datePosted = startTime.AddDays(h);
l.Add(a);
}
return l;
}
I have an old system which uses UpdatePanels of asp.net
After the postback is completed, we know that the inside of UpdatePanel is updated
Can i delay this update somehow on the client side ? is that possible?
So it will be like, when the postback is started, i set a javascript datetime object on the client side
Once the postback is completed, and the data is returned from the server, before updating the client side interface, i check how many miliseconds has passed and I delay the update of the client side until certain miliseconds has passed
is this possible?
asp.net 4.5 c#
let me clarify better
i want each update of the page to be exactly 500 miliseconds after the ajax postback request started
however the server delay is unknown and changes for the every location
let say that for person 1 the server delay is 122 ms
for person 2 the server delay is 234
for person 3 the server delay is 444
so i would be have to delay the page update at the client side
for the person 1 : 378 ms
for the person 2 : 266 ms
for the person 3 : 56 ms
i have checked and i found that there is a function :
Sys.WebForms.PageRequestManager pageLoading Event
so if i can somehow override the function that this function calls to update the page i can achieve
(i still dont know what function it calls to complete the update operation on the client side)
lets assume that inside
Sys.WebForms.PageRequestManager pageLoading Event
updateTheChanges function is called
so if i can override this updateTheChanges function and call it with a delay i can achieve what i want
I need exactly something like this which will overwrite the update function of the updatepanel. So i can call this function with a delay
ASP.Net Webforms w/ AJAX Slow Rendering
ty
here the web resource files
script resource 1 : http://pastebin.com/0rSCMn3g
script resource 2 : http://pastebin.com/GvqwpPv8
script resource 3 below
function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit) {
this.eventTarget = eventTarget;
this.eventArgument = eventArgument;
this.validation = validation;
this.validationGroup = validationGroup;
this.actionUrl = actionUrl;
this.trackFocus = trackFocus;
this.clientSubmit = clientSubmit;
}
function WebForm_DoPostBackWithOptions(options) {
var validationResult = true;
if (options.validation) {
if (typeof(Page_ClientValidate) == 'function') {
validationResult = Page_ClientValidate(options.validationGroup);
}
}
if (validationResult) {
if ((typeof(options.actionUrl) != "undefined") && (options.actionUrl != null) && (options.actionUrl.length > 0)) {
theForm.action = options.actionUrl;
}
if (options.trackFocus) {
var lastFocus = theForm.elements["__LASTFOCUS"];
if ((typeof(lastFocus) != "undefined") && (lastFocus != null)) {
if (typeof(document.activeElement) == "undefined") {
lastFocus.value = options.eventTarget;
} else {
var active = document.activeElement;
if ((typeof(active) != "undefined") && (active != null)) {
if ((typeof(active.id) != "undefined") && (active.id != null) && (active.id.length > 0)) {
lastFocus.value = active.id;
} else if (typeof(active.name) != "undefined") {
lastFocus.value = active.name;
}
}
}
}
}
}
if (options.clientSubmit) {
__doPostBack(options.eventTarget, options.eventArgument);
}
}
var __pendingCallbacks = new Array();
var __synchronousCallBackIndex = -1;
function WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync) {
var postData = __theFormPostData +
"__CALLBACKID=" + WebForm_EncodeCallback(eventTarget) +
"&__CALLBACKPARAM=" + WebForm_EncodeCallback(eventArgument);
if (theForm["__EVENTVALIDATION"]) {
postData += "&__EVENTVALIDATION=" + WebForm_EncodeCallback(theForm["__EVENTVALIDATION"].value);
}
var xmlRequest, e;
try {
xmlRequest = new XMLHttpRequest();
} catch (e) {
try {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
var setRequestHeaderMethodExists = true;
try {
setRequestHeaderMethodExists = (xmlRequest && xmlRequest.setRequestHeader);
} catch (e) {}
var callback = new Object();
callback.eventCallback = eventCallback;
callback.context = context;
callback.errorCallback = errorCallback;
callback.async = useAsync;
var callbackIndex = WebForm_FillFirstAvailableSlot(__pendingCallbacks, callback);
if (!useAsync) {
if (__synchronousCallBackIndex != -1) {
__pendingCallbacks[__synchronousCallBackIndex] = null;
}
__synchronousCallBackIndex = callbackIndex;
}
if (setRequestHeaderMethodExists) {
xmlRequest.onreadystatechange = WebForm_CallbackComplete;
callback.xmlRequest = xmlRequest;
// e.g. http:
var action = theForm.action || document.location.pathname,
fragmentIndex = action.indexOf('#');
if (fragmentIndex !== -1) {
action = action.substr(0, fragmentIndex);
}
if (!__nonMSDOMBrowser) {
var queryIndex = action.indexOf('?');
if (queryIndex !== -1) {
var path = action.substr(0, queryIndex);
if (path.indexOf("%") === -1) {
action = encodeURI(path) + action.substr(queryIndex);
}
} else if (action.indexOf("%") === -1) {
action = encodeURI(action);
}
}
xmlRequest.open("POST", action, true);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
xmlRequest.send(postData);
return;
}
callback.xmlRequest = new Object();
var callbackFrameID = "__CALLBACKFRAME" + callbackIndex;
var xmlRequestFrame = document.frames[callbackFrameID];
if (!xmlRequestFrame) {
xmlRequestFrame = document.createElement("IFRAME");
xmlRequestFrame.width = "1";
xmlRequestFrame.height = "1";
xmlRequestFrame.frameBorder = "0";
xmlRequestFrame.id = callbackFrameID;
xmlRequestFrame.name = callbackFrameID;
xmlRequestFrame.style.position = "absolute";
xmlRequestFrame.style.top = "-100px"
xmlRequestFrame.style.left = "-100px";
try {
if (callBackFrameUrl) {
xmlRequestFrame.src = callBackFrameUrl;
}
} catch (e) {}
document.body.appendChild(xmlRequestFrame);
}
var interval = window.setInterval(function() {
xmlRequestFrame = document.frames[callbackFrameID];
if (xmlRequestFrame && xmlRequestFrame.document) {
window.clearInterval(interval);
xmlRequestFrame.document.write("");
xmlRequestFrame.document.close();
xmlRequestFrame.document.write('<html><body><form method="post"><input type="hidden" name="__CALLBACKLOADSCRIPT" value="t"></form></body></html>');
xmlRequestFrame.document.close();
xmlRequestFrame.document.forms[0].action = theForm.action;
var count = __theFormPostCollection.length;
var element;
for (var i = 0; i < count; i++) {
element = __theFormPostCollection[i];
if (element) {
var fieldElement = xmlRequestFrame.document.createElement("INPUT");
fieldElement.type = "hidden";
fieldElement.name = element.name;
fieldElement.value = element.value;
xmlRequestFrame.document.forms[0].appendChild(fieldElement);
}
}
var callbackIdFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIdFieldElement.type = "hidden";
callbackIdFieldElement.name = "__CALLBACKID";
callbackIdFieldElement.value = eventTarget;
xmlRequestFrame.document.forms[0].appendChild(callbackIdFieldElement);
var callbackParamFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackParamFieldElement.type = "hidden";
callbackParamFieldElement.name = "__CALLBACKPARAM";
callbackParamFieldElement.value = eventArgument;
xmlRequestFrame.document.forms[0].appendChild(callbackParamFieldElement);
if (theForm["__EVENTVALIDATION"]) {
var callbackValidationFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackValidationFieldElement.type = "hidden";
callbackValidationFieldElement.name = "__EVENTVALIDATION";
callbackValidationFieldElement.value = theForm["__EVENTVALIDATION"].value;
xmlRequestFrame.document.forms[0].appendChild(callbackValidationFieldElement);
}
var callbackIndexFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIndexFieldElement.type = "hidden";
callbackIndexFieldElement.name = "__CALLBACKINDEX";
callbackIndexFieldElement.value = callbackIndex;
xmlRequestFrame.document.forms[0].appendChild(callbackIndexFieldElement);
xmlRequestFrame.document.forms[0].submit();
}
}, 10);
}
function WebForm_CallbackComplete() {
for (var i = 0; i < __pendingCallbacks.length; i++) {
callbackObject = __pendingCallbacks[i];
if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) {
if (!__pendingCallbacks[i].async) {
__synchronousCallBackIndex = -1;
}
__pendingCallbacks[i] = null;
var callbackFrameID = "__CALLBACKFRAME" + i;
var xmlRequestFrame = document.getElementById(callbackFrameID);
if (xmlRequestFrame) {
xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
}
WebForm_ExecuteCallback(callbackObject);
}
}
}
function WebForm_ExecuteCallback(callbackObject) {
var response = callbackObject.xmlRequest.responseText;
if (response.charAt(0) == "s") {
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(1), callbackObject.context);
}
} else if (response.charAt(0) == "e") {
if ((typeof(callbackObject.errorCallback) != "undefined") && (callbackObject.errorCallback != null)) {
callbackObject.errorCallback(response.substring(1), callbackObject.context);
}
} else {
var separatorIndex = response.indexOf("|");
if (separatorIndex != -1) {
var validationFieldLength = parseInt(response.substring(0, separatorIndex));
if (!isNaN(validationFieldLength)) {
var validationField = response.substring(separatorIndex + 1, separatorIndex + validationFieldLength + 1);
if (validationField != "") {
var validationFieldElement = theForm["__EVENTVALIDATION"];
if (!validationFieldElement) {
validationFieldElement = document.createElement("INPUT");
validationFieldElement.type = "hidden";
validationFieldElement.name = "__EVENTVALIDATION";
theForm.appendChild(validationFieldElement);
}
validationFieldElement.value = validationField;
}
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(separatorIndex + validationFieldLength + 1), callbackObject.context);
}
}
}
}
}
function WebForm_FillFirstAvailableSlot(array, element) {
var i;
for (i = 0; i < array.length; i++) {
if (!array[i]) break;
}
array[i] = element;
return i;
}
var __nonMSDOMBrowser = (window.navigator.appName.toLowerCase().indexOf('explorer') == -1);
var __theFormPostData = "";
var __theFormPostCollection = new Array();
var __callbackTextTypes = /^(text|password|hidden|search|tel|url|email|number|range|color|datetime|date|month|week|time|datetime-local)$/i;
function WebForm_InitCallback() {
var formElements = theForm.elements,
count = formElements.length,
element;
for (var i = 0; i < count; i++) {
element = formElements[i];
var tagName = element.tagName.toLowerCase();
if (tagName == "input") {
var type = element.type;
if ((__callbackTextTypes.test(type) || ((type == "checkbox" || type == "radio") && element.checked)) && (element.id != "__EVENTVALIDATION")) {
WebForm_InitCallbackAddField(element.name, element.value);
}
} else if (tagName == "select") {
var selectCount = element.options.length;
for (var j = 0; j < selectCount; j++) {
var selectChild = element.options[j];
if (selectChild.selected == true) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
} else if (tagName == "textarea") {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
function WebForm_InitCallbackAddField(name, value) {
var nameValue = new Object();
nameValue.name = name;
nameValue.value = value;
__theFormPostCollection[__theFormPostCollection.length] = nameValue;
__theFormPostData += WebForm_EncodeCallback(name) + "=" + WebForm_EncodeCallback(value) + "&";
}
function WebForm_EncodeCallback(parameter) {
if (encodeURIComponent) {
return encodeURIComponent(parameter);
} else {
return escape(parameter);
}
}
var __disabledControlArray = new Array();
function WebForm_ReEnableControls() {
if (typeof(__enabledControlArray) == 'undefined') {
return false;
}
var disabledIndex = 0;
for (var i = 0; i < __enabledControlArray.length; i++) {
var c;
if (__nonMSDOMBrowser) {
c = document.getElementById(__enabledControlArray[i]);
} else {
c = document.all[__enabledControlArray[i]];
}
if ((typeof(c) != "undefined") && (c != null) && (c.disabled == true)) {
c.disabled = false;
__disabledControlArray[disabledIndex++] = c;
}
}
setTimeout("WebForm_ReDisableControls()", 0);
return true;
}
function WebForm_ReDisableControls() {
for (var i = 0; i < __disabledControlArray.length; i++) {
__disabledControlArray[i].disabled = true;
}
}
function WebForm_SimulateClick(element, event) {
var clickEvent;
if (element) {
if (element.click) {
element.click();
} else {
clickEvent = document.createEvent("MouseEvents");
clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
if (!element.dispatchEvent(clickEvent)) {
return true;
}
}
event.cancelBubble = true;
if (event.stopPropagation) {
event.stopPropagation();
}
return false;
}
return true;
}
function WebForm_FireDefaultButton(event, target) {
if (event.keyCode == 13) {
var src = event.srcElement || event.target;
if (src &&
((src.tagName.toLowerCase() == "input") &&
(src.type.toLowerCase() == "submit" || src.type.toLowerCase() == "button")) ||
((src.tagName.toLowerCase() == "a") &&
(src.href != null) && (src.href != "")) ||
(src.tagName.toLowerCase() == "textarea")) {
return true;
}
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
} else {
defaultButton = document.all[target];
}
if (defaultButton) {
return WebForm_SimulateClick(defaultButton, event);
}
}
return true;
}
function WebForm_GetScrollX() {
if (__nonMSDOMBrowser) {
return window.pageXOffset;
} else {
if (document.documentElement && document.documentElement.scrollLeft) {
return document.documentElement.scrollLeft;
} else if (document.body) {
return document.body.scrollLeft;
}
}
return 0;
}
function WebForm_GetScrollY() {
if (__nonMSDOMBrowser) {
return window.pageYOffset;
} else {
if (document.documentElement && document.documentElement.scrollTop) {
return document.documentElement.scrollTop;
} else if (document.body) {
return document.body.scrollTop;
}
}
return 0;
}
function WebForm_SaveScrollPositionSubmit() {
if (__nonMSDOMBrowser) {
theForm.elements['__SCROLLPOSITIONY'].value = window.pageYOffset;
theForm.elements['__SCROLLPOSITIONX'].value = window.pageXOffset;
} else {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
}
if ((typeof(this.oldSubmit) != "undefined") && (this.oldSubmit != null)) {
return this.oldSubmit();
}
return true;
}
function WebForm_SaveScrollPositionOnSubmit() {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
if ((typeof(this.oldOnSubmit) != "undefined") && (this.oldOnSubmit != null)) {
return this.oldOnSubmit();
}
return true;
}
function WebForm_RestoreScrollPosition() {
if (__nonMSDOMBrowser) {
window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value);
} else {
window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value);
}
if ((typeof(theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) {
return theForm.oldOnLoad();
}
return true;
}
function WebForm_TextBoxKeyHandler(event) {
if (event.keyCode == 13) {
var target;
if (__nonMSDOMBrowser) {
target = event.target;
} else {
target = event.srcElement;
}
if ((typeof(target) != "undefined") && (target != null)) {
if (typeof(target.onchange) != "undefined") {
target.onchange();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
}
return true;
}
function WebForm_TrimString(value) {
return value.replace(/^\s+|\s+$/g, '')
}
function WebForm_AppendToClassName(element, className) {
var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
className = WebForm_TrimString(className);
var index = currentClassName.indexOf(' ' + className + ' ');
if (index === -1) {
element.className = (element.className === '') ? className : element.className + ' ' + className;
}
}
function WebForm_RemoveClassName(element, className) {
var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
className = WebForm_TrimString(className);
var index = currentClassName.indexOf(' ' + className + ' ');
if (index >= 0) {
element.className = WebForm_TrimString(currentClassName.substring(0, index) + ' ' +
currentClassName.substring(index + className.length + 1, currentClassName.length));
}
}
function WebForm_GetElementById(elementId) {
if (document.getElementById) {
return document.getElementById(elementId);
} else if (document.all) {
return document.all[elementId];
} else return null;
}
function WebForm_GetElementByTagName(element, tagName) {
var elements = WebForm_GetElementsByTagName(element, tagName);
if (elements && elements.length > 0) {
return elements[0];
} else return null;
}
function WebForm_GetElementsByTagName(element, tagName) {
if (element && tagName) {
if (element.getElementsByTagName) {
return element.getElementsByTagName(tagName);
}
if (element.all && element.all.tags) {
return element.all.tags(tagName);
}
}
return null;
}
function WebForm_GetElementDir(element) {
if (element) {
if (element.dir) {
return element.dir;
}
return WebForm_GetElementDir(element.parentNode);
}
return "ltr";
}
function WebForm_GetElementPosition(element) {
var result = new Object();
result.x = 0;
result.y = 0;
result.width = 0;
result.height = 0;
if (element.offsetParent) {
result.x = element.offsetLeft;
result.y = element.offsetTop;
var parent = element.offsetParent;
while (parent) {
result.x += parent.offsetLeft;
result.y += parent.offsetTop;
var parentTagName = parent.tagName.toLowerCase();
if (parentTagName != "table" &&
parentTagName != "body" &&
parentTagName != "html" &&
parentTagName != "div" &&
parent.clientTop &&
parent.clientLeft) {
result.x += parent.clientLeft;
result.y += parent.clientTop;
}
parent = parent.offsetParent;
}
} else if (element.left && element.top) {
result.x = element.left;
result.y = element.top;
} else {
if (element.x) {
result.x = element.x;
}
if (element.y) {
result.y = element.y;
}
}
if (element.offsetWidth && element.offsetHeight) {
result.width = element.offsetWidth;
result.height = element.offsetHeight;
} else if (element.style && element.style.pixelWidth && element.style.pixelHeight) {
result.width = element.style.pixelWidth;
result.height = element.style.pixelHeight;
}
return result;
}
function WebForm_GetParentByTagName(element, tagName) {
var parent = element.parentNode;
var upperTagName = tagName.toUpperCase();
while (parent && (parent.tagName.toUpperCase() != upperTagName)) {
parent = parent.parentNode ? parent.parentNode : parent.parentElement;
}
return parent;
}
function WebForm_SetElementHeight(element, height) {
if (element && element.style) {
element.style.height = height + "px";
}
}
function WebForm_SetElementWidth(element, width) {
if (element && element.style) {
element.style.width = width + "px";
}
}
function WebForm_SetElementX(element, x) {
if (element && element.style) {
element.style.left = x + "px";
}
}
function WebForm_SetElementY(element, y) {
if (element && element.style) {
element.style.top = y + "px";
}
}
Here is a way to delay the UpdatePanel refresh without freezing the user interface:
In the pageLoading event handler, save the ID and the previous HTML of the panels to be updated
In the pageLoad event handler, save the new HTML of the panels but replace it by the old one
After the delay expires, set the new HTML in the updated panels
Here is the client code:
<script type="text/javascript">
var updateTime = 0;
var updatedPanelArray = [];
function setUpdateTime() {
updateTime = new Date(Date.now() + 500);
}
function pageLoading(sender, e) {
updatedPanelArray.length = 0;
var panels = e.get_panelsUpdating();
for (var i = 0; i < panels.length; i++) {
var pnl = panels[i];
updatedPanelArray.push({ id: pnl.id, oldHTML: pnl.innerHTML });
}
}
function pageLoad(sender, e) {
if (e.get_isPartialLoad()) {
for (var i = 0; i < updatedPanelArray.length; i++) {
var updatedPanel = updatedPanelArray[i];
var pnl = document.getElementById(updatedPanel.id);
updatedPanel.newHTML = pnl.innerHTML;
pnl.innerHTML = updatedPanel.oldHTML;
setTimeout(refreshUpdatePanel, updateTime - Date.now());
}
}
}
function refreshUpdatePanel() {
for (var i = 0; i < updatedPanelArray.length; i++) {
var updatedPanel = updatedPanelArray[i];
var pnl = document.getElementById(updatedPanel.id);
pnl.innerHTML = updatedPanel.newHTML;
}
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoading);
</script>
The update time is set before triggering the asynchronous postback:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblUpdatePanel1" runat="server" />
<asp:Button ID="btnUpdatePanel" runat="server" OnClientClick="setUpdateTime();" OnClick="btnUpdatePanel_Click" />
</ContentTemplate>
</asp:UpdatePanel>
It can be tested with the following event handler in code-behind (suggestion: set the delay to 5000 ms in the Javascript code to make it obvious):
protected void btnUpdatePanel_Click(object sender, EventArgs e)
{
lblUpdatePanel1.Text = DateTime.Now.ToString();
}
If you don't mind the user interface being frozen while waiting, you can delay the refresh by keeping the pageLoad event handler busy until the delay expires:
<script type="text/javascript">
var updateTime = 0;
function setUpdateTime() {
updateTime = new Date(Date.now() + 500);
}
function pageLoad(sender, e) {
if (e.get_isPartialLoad()) {
while (Date.now() < updateTime) {
// Loop until the delay expires
}
}
}
</script>
You can initialize the update time before triggering the asynchronous postback:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
...
<asp:Button ID="btn1" runat="server" OnClientClick="setUpdateTime();" ... />
</ContentTemplate>
</asp:UpdatePanel>
Use UpdatePanel.UpdateMode Property to gets or sets a value that indicates when an UpdatePanel control's content is updated. For more details visit this link.
You could delay the server side, so all the delays would be more or less equals for everyone.
If this is not an option, you could have a hidden field inside the update panel (or somewhere else). The function that handles the update (in the server side) would calculate the time it took execute, and before finishing, would update this hidden field. Now back in the client side, check the value of this field and calculate the difference between this value and yours 500ms. You could use datetimes or milliseconds.
It's not the prettiest solution but imho, this is not a frequent problem that people want to handle (in fact, I dont think that you should delay a faster response to the slowest one)
I am having some trouble with the verse button. i am not sure what I am doing wrong but I need to make it where the user presses the verse button and it adds the textview of the word "Verse" to the list that was created. Please help. What am I doing wrong. This was written for Android using C# in Xamarin by the way.
namespace Songression
{
public class CheckRect{
public int top{ get; set; }
public int height{ get; set; }
}
[Activity (Label = "Songression")]
public class results : Activity, View.IOnTouchListener
{
//CheckBox[] check;
List<LinearLayout> linearSet;
//List<CheckRect> rectList;
ScrollView scrollView;
EditText editText = null;
LinearLayout view;
bool moveOrEdit = false;
int screenWidth;
List<String> checkTextList;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.results);
var metrics = Resources.DisplayMetrics;
screenWidth = metrics.WidthPixels;
//var widthInDp = ConvertPixelsToDp(metrics.WidthPixels);
view = FindViewById<LinearLayout> (Resource.Id.linearlayout0);
checkTextList = new List<String>();
checkTextList.Add ("10 bucks in your pocket and barely making it.");
checkTextList.Add ("100 steps to the water");
checkTextList.Add ("18 and going to Hollywood");
checkTextList.Add ("3 years to propose");
String checkTextSet = Intent.GetStringExtra ("MyData") ?? "";
if (checkTextSet == null || checkTextSet == "") {
} else {
String[] textSet = checkTextSet.Split (',');
checkTextList.AddRange (textSet);
}
//Back Button
Button buttonBack = FindViewById<Button> (Resource.Id.buttonBack);
buttonBack.Click += delegate {
Finish();
};
///
//AddLine Button
Button buttonAdd = FindViewById<Button> (Resource.Id.buttonAdd);
buttonAdd.Click += delegate {
addTextPro(false,"");
};
///
//Add Verse
//Button buttonVerse = FindViewById <Button> (Resource.Id.buttonVerse);
//buttonVerse.Click += delegate {
// checkTextList.Add("Verse"));
//};
{
///
//Email Button
Button buttonEmail = FindViewById<Button> (Resource.Id.buttonEmail);
buttonEmail.Click += delegate {
runEmailPro ();
};
scrollView = FindViewById<ScrollView> (Resource.Id.scrollview0);
List<String> resultList = new List<String> ();
int count = checkTextList.Count;//myResources.check_indexSet.Count;
linearSet = new List<LinearLayout> ();
for (int index = 0; index < view.ChildCount; index++) {
view.RemoveViewAt (index);
}
///
//Initiate Rect and Check
if (myResources.isLast == false) {
for (int index = 0; index < count; index++) {
InitiateWidgets (index, false);
}
} else {
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
var lastPath = Path.Combine (sdCardPath, "lastlasttxt.txt");
String fileNamePath = Path.Combine (sdCardPath, readFileSdcardFile (lastPath));
String loadData;
if (File.Exists (fileNamePath))
loadData = File.ReadAllText (fileNamePath);
else
return;
String[] splitData = loadData.Split ('\n');
foreach (String item in splitData) {
if (item.CompareTo ("") == 0)
continue;
if (item [0] == 't') {
addTextPro (true, item.Substring (1));
}
if (item [0] == 'c') {
bool bChecked = false;
if (item [1] != '0') {
bChecked = true;
} else {
bChecked = false;
}
InitiateWidgets (0, true, item.Substring (2), bChecked);
}
}
}
///
//save function
Button buttonSave = FindViewById<Button> (Resource.Id.buttonSave);
buttonSave.Click += delegate {
saveResultPro ();
};
///
//move function
Button buttonMove = FindViewById<Button> (Resource.Id.buttonMove);
buttonMove.Text = "Move";
buttonMove.Click += delegate {
removeAllFocus (moveOrEdit);
if (moveOrEdit == false) {
buttonMove.Text = "Edit";
moveOrEdit = true;
} else {
buttonMove.Text = "Move";
moveOrEdit = false;
}
};
//final function
Button buttonFinal = FindViewById<Button> (Resource.Id.buttonFinal);
buttonFinal.Click += delegate {
var fResults = new Intent (this, typeof(finalResults));
fResults.PutExtra ("MyData", getAllInfo ());
StartActivity (fResults);
};
}
}
//wirte the file on the sdcard.
public void writeFileSdcardFile(String path,String write_str,bool bTitle){
if (bTitle == true) {
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
var lastPath = Path.Combine(sdCardPath,"lastlasttxt.txt");
if (File.Exists (path) == false) {
File.WriteAllText (path, write_str);
}
else {
String[] existFile = readFileSdcardFile (path).Split('\n');
foreach (String item in existFile) {
if (write_str.Substring (0, write_str.Length - 1).CompareTo (item) == 0) {
File.WriteAllText (lastPath, write_str.Substring (0, write_str.Length - 1));
return;
}
}
File.AppendAllText (path, write_str);
}
File.WriteAllText (lastPath, write_str.Substring(0, write_str.Length - 1));
} else {
File.WriteAllText (path, write_str);
}
}
public String readFileSdcardFile(String path) {
if (File.Exists (path))
return File.ReadAllText (path);
else
return "";
}
public String getAllInfo()
{
String extra = "";
foreach(LinearLayout linear in linearSet)
{
var widgetType = linear.GetChildAt (0).GetType ().ToString ();
if (widgetType.CompareTo ("Android.Widget.EditText") == 0) {
EditText editText = (EditText)linear.GetChildAt (0);
extra += editText.Text + "\n";
} else if (widgetType.CompareTo ("Android.Widget.CheckBox") == 0) {
CheckBox checBox = (CheckBox)linear.GetChildAt (0);
if (checBox.Checked == true)
extra +="1" + checBox.Text + "\n";
else
extra +="0" + checBox.Text + "\n";
}
}
return extra;
}
//
//run email pro
public void runEmailPro(){
var email = new Intent (Android.Content.Intent.ActionSend);
email.PutExtra (Android.Content.Intent.ExtraEmail,
new string[]{"person1#xamarin.com", "person2#xamrin.com"} );
email.PutExtra (Android.Content.Intent.ExtraCc,
new string[]{"person3#xamarin.com"} );
email.PutExtra (Android.Content.Intent.ExtraSubject, "Hello Email");
email.PutExtra (Android.Content.Intent.ExtraText,
getAllInfo());
email.SetType ("message/rfc822");
StartActivity (email);
}
//
// add Text code
public void addTextPro(bool bLast,String textWidget)
{
LinearLayout linear = new LinearLayout (this);
ImageView imgView = new ImageView (this);
imgView.SetImageResource (Resource.Drawable.delete123);
editText = new EditText (this);
editText.SetSingleLine ();
editText.SetWidth(screenWidth - 50);
if (bLast)
editText.Text = textWidget;
if (moveOrEdit == true)
editText.SetOnTouchListener (this);
else
editText.SetOnTouchListener (null);
linear.AddView(editText);
linear.AddView(imgView);
//delete function.
imgView.Click += delegate {
deleteMessage(imgView);
};
linearSet.Add(linear);
view.AddView(linear);
}
//
//delete message
public void deleteMessage(ImageView imgView)
{
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Delete Phrase!");
builder.SetMessage ("Are you sure you would like to delete this phrase?");
builder.SetPositiveButton("Yes", (sender, args) => {
// Yes button
LinearLayout parent = (LinearLayout)imgView.Parent;
parent.Visibility = ViewStates.Invisible;
int childIndex = view.IndexOfChild(parent);
view.RemoveView(parent);
linearSet.Remove(parent);});
builder.SetNegativeButton("No", (sender, args) => {});
builder.SetCancelable(false);
builder.Show ();
}
//
//save Result
public void saveResultPro()
{
var factory = LayoutInflater.From(this);
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Song Name");
EditText songText = new EditText (this);
builder.SetView (songText);
//builder.SetView(factory.Inflate(Resource.Layout.saveDialog,
// FindViewById<ViewGroup>(Resource.Id.saveDialog)));
builder.SetPositiveButton("OK", (sender, args) => {
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
//EditText songText = FindViewById<EditText> (Resource.Id.projectName);
var textPath = Path.Combine(sdCardPath,songText.Text);
var textTitlePath = Path.Combine(sdCardPath,"Titles.txt");
String saveData = "";
foreach(LinearLayout linear in linearSet)
{
var widgetType = linear.GetChildAt (0).GetType ().ToString ();
if (widgetType.CompareTo ("Android.Widget.EditText") == 0) {
EditText editText = (EditText)linear.GetChildAt (0);
saveData += "t" + editText.Text + "\n";
} else if (widgetType.CompareTo ("Android.Widget.CheckBox") == 0) {
CheckBox checBox = (CheckBox)linear.GetChildAt (0);
if (checBox.Checked == true)
saveData += "c1" + checBox.Text + "\n";
else
saveData += "c0" + checBox.Text + "\n";
}
}
writeFileSdcardFile(textTitlePath,songText.Text + "\n",true);
writeFileSdcardFile(textPath,saveData,false);
});
builder.SetNegativeButton("Cancel", (sender, args) => {});
builder.SetCancelable(false);
builder.Show ();
}
//remove All focus
public void removeAllFocus(bool flag){
View.IOnTouchListener context = null;
if (flag == false){
context = this;
}
else{
context = null;
}
foreach (LinearLayout linear in linearSet) {
var widgetType = linear.GetChildAt (0).GetType ().ToString ();
if (widgetType.CompareTo ("Android.Widget.EditText") == 0) {
EditText editText = (EditText)linear.GetChildAt (0);
editText.SetOnTouchListener (context);
} else if (widgetType.CompareTo ("Android.Widget.CheckBox") == 0) {
CheckBox checBox = (CheckBox)linear.GetChildAt (0);
checBox.SetOnTouchListener (context);
}
}
scrollView.SetOnTouchListener (context);
}
//
//initiate widgets
public void InitiateWidgets(int index,bool bLast,String widgetText = "", bool bSel = false){
LinearLayout linear = new LinearLayout (this);
CheckBox check = new CheckBox(this);
ImageView imgView = new ImageView (this);
//delete function.
imgView.Click += delegate {
deleteMessage(imgView);
};
if (bLast == false) {
//int stringIndex = Resource.String.checkname0 + myResources.check_indexSet [index];
check.Text = checkTextList[index];
if (index < 4) {
if (myResources.check_index [index] == 1)
check.Checked = true;
else {
check.Checked = false;
}
} else {
check.Checked = true;
}
} else {
check.Text = widgetText;
check.Checked = bSel;
}
check.SetWidth (screenWidth - 55);
check.SetOnTouchListener (null);
imgView.SetImageResource (Resource.Drawable.delete123);
linear.AddView (check);
linear.AddView (imgView);
linearSet.Add(linear);
view.AddView (linear);
scrollView.SetOnTouchListener (null);
}
//
//Touch Event
float _viewY = 0;
//bool flag = false;
bool check_flag = false;
LinearLayout parentLayout;
int selTop;
int selBottom;
bool downFlag = false;
public bool OnTouch(View v, MotionEvent e)
{
switch (e.Action)
{
case MotionEventActions.Down:
if (v != scrollView) {
_viewY = e.GetY ();
parentLayout = (LinearLayout)v.Parent;
selTop = parentLayout.Top;
selBottom = parentLayout.Bottom;
check_flag = true;
downFlag = true;
}
break;
case MotionEventActions.Move:
if (v == scrollView && downFlag == true) {
var top = (int)(e.GetY () - _viewY);
var bottom = (int)(top + 55);
parentLayout.Layout (parentLayout.Left, top, parentLayout.Right, bottom);
check_flag = false;
}
break;
case MotionEventActions.Up:
if (downFlag == false)
return true;
if (parentLayout == null)
return true;
int originalPos = 0;
int placePos = -1;
downFlag = false;
if (parentLayout.GetChildAt(0).GetType ().ToString ().CompareTo ("Android.Widget.CheckBox") == 0) {
if (check_flag == true) {
CheckBox selCheck = (CheckBox)parentLayout.GetChildAt (0);
if (selCheck.Checked == false) {
selCheck.Checked = true;
} else {
selCheck.Checked = false;
}
check_flag = false;
return true;
}
}
if (parentLayout.GetChildAt(0).GetType ().ToString ().CompareTo ("Android.Widget.EditText") == 0) {
if (check_flag == true) {
EditText selText = (EditText)parentLayout.GetChildAt (0);
check_flag = false;
return true;
}
}
if (v == scrollView) {
int linearCount = linearSet.Count;
int index;
for (index = 0; index < linearCount; index++) {
if (parentLayout == linearSet [index]) {
originalPos = index;
break;
}
}
//Laying position.
for (index = 0; index < linearCount; index++) {
if (originalPos == index)
continue;
if (linearSet[originalPos].Top < linearSet [index].Top) {
if (originalPos == index - 1) {
linearSet[originalPos].Layout (linearSet[originalPos].Left,
selTop, linearSet[originalPos].Right,
selBottom);
return true;
} else {
if (index > originalPos) {
placePos = index - 1;
break;
} else {
placePos = index;
break;
}
}
}
/*if (linearSet [originalPos].Top == linearSet [index].Top) {
linearSet[originalPos].Layout (linearSet[originalPos].Left,
selTop, linearSet[originalPos].Right,
selBottom);
return true;
}*/
}
//Is original pos?
if ((originalPos == linearCount - 1) && (placePos == -1)) {
linearSet[originalPos].Layout (linearSet[originalPos].Left, selTop,
linearSet[originalPos].Right, selBottom);
return true;
}
if (placePos == -1)
placePos = linearCount - 1;
//Change the position on the result page.
int orgTop;
int orgBottom;
orgTop = linearSet [originalPos].Top;
orgBottom = linearSet [originalPos].Bottom;
linearSet [originalPos].Layout (linearSet[originalPos].Left, linearSet [placePos].Top,
linearSet[originalPos].Right, linearSet [placePos].Bottom);
LinearLayout tempLinear = linearSet [originalPos];
if (originalPos >= placePos) {
for (index = originalPos - 1; index >= placePos; index--) {
linearSet [index].Layout (linearSet[originalPos].Left, linearSet [index + 1].Top,
linearSet[originalPos].Right, linearSet [index + 1].Bottom);
linearSet [index + 1] = linearSet [index];
}
} else {
for (index = originalPos + 1; index <= placePos; index++){
linearSet [index].Layout (linearSet[originalPos].Left, linearSet [index - 1].Top,
linearSet[originalPos].Right, linearSet [index - 1].Bottom);
linearSet [index - 1] = linearSet [index];
}
}
linearSet [placePos] = tempLinear;
linearSet [placePos].Layout (linearSet[placePos].Left, orgTop,
linearSet[placePos].Right, orgBottom);
view.RemoveViews (0, view.ChildCount);
for (index = 0; index < linearSet.Count; index++) {
view.AddView(linearSet[index]);
}
}
break;
}
return true;
}
}
}
You missed to register listener to the Button click and override onClick
I am working on a project where I am creating a dynamic table.Now depending upon my condition I am adding link button to table cells,but the click event of my link button is not working.I am not getting why its not working,neither its showing any error.
Following is my code
public void makeCalendar()
{
tblcalendar.Rows.Clear();
//for current month
DateTime startingdate = StartDateOfMonth(DateTime.Now.AddMonths(monthclickedno));
DateTime enddate = EndDateOfMonth(DateTime.Now.AddMonths(monthclickedno));
string startingday = startingdate.DayOfWeek.ToString();
int startingdayno = Convert.ToInt32(startingdate.DayOfWeek);
string endday = enddate.DayOfWeek.ToString();//like saturday is 6,stating is from monday with 1 and ending is sunday with 7
int enddayno = Convert.ToInt32(enddate.DayOfWeek);
//for prevoius month
DateTime enddateprevious = (EndDateOfMonth(DateTime.Now.AddMonths(monthclickedno)));
//for next month
DateTime startingdatenext = StartDateOfMonth(DateTime.Now.AddMonths(1));
DateTime dtstart=startingdate.AddDays(-(startingdayno+1));
//sMonthName = "January";
//int iMonthNo = Convert.ToDateTime("01-" + sMonthName + "-2011").Month;
for (int i = 0; i <7;i++)
{
TableRow tr = new TableRow();
for (int j = 0; j < 7;j++ )
{
TableCell tc = new TableCell();
clickablecell ctCell = new clickablecell();
//tc.ID = idtc.ToString();
idtc++;
if(i==0)
{
tr.CssClass = "firstrow";
tc.CssClass = "firstrowcell";
if (j == 0)
tc.Text = "Sun";
else if (j == 1)
tc.Text = "Mon";
else if (j == 2)
tc.Text = "Tue";
else if (j == 3)
tc.Text = "Wed";
else if (j == 4)
tc.Text = "Thu";
else if (j == 5)
tc.Text = "Fri";
else if (j == 6)
tc.Text = "Sat";
tr.Cells.Add(tc);
}
else{
tc.CssClass = "othercells";
dtstart=dtstart.AddDays(1);
//if date is single digit like 1,2
if (dtstart.ToString("dd").Substring(0, (dtstart.ToString("dd").Length)-1) == "0")
ctCell.Text = (dtstart.ToString("dd").Substring(1));
else
ctCell.Text = (dtstart.ToString("dd"));
ctCell.Attributes.Add("onmouseover", "defColor=this.style.backgroundColor; this.style.backgroundColor='LightGray';");
ctCell.Attributes.Add("onmouseout", "this.style.backgroundColor=defColor;");
//ctCell.ID = k.ToString();
k++;
ctCell.Click += new clickablecell.ClickEventHandler(textcell_Click);
//check for events in this date
DataTable dtevents = checkEvents(dtstart.ToString("dd-MM-yyyy"));
if (dtevents.Rows.Count != 0)
{
LinkButton lnkevent = new LinkButton();
//lnkevent.ClientIDMode ="Static";
lnkevent.ID = (i+j).ToString();
if (dtevents.Rows.Count == 1)
{
if (dtevents.Rows[0]["eventtype"].ToString() == "Holiday")
{
lnkevent.Text = dtevents.Rows[0]["eventtype"].ToString();
lnkevent.CssClass = "tcholidaytext";
ctCell.CssClass = "tcholidaytext";
}
else if (dtevents.Rows[0]["eventtype"].ToString() == "Event")
{
lnkevent.Text = dtevents.Rows[0]["eventtype"].ToString();
lnkevent.CssClass = "tceventtext";
ctCell.CssClass = "tceventtext";
}
else
{
lnkevent.Text = dtevents.Rows[0]["eventtype"].ToString();
lnkevent.CssClass = "tcimpdaytext";
ctCell.CssClass = "tcimpdaytext";
}
}
else
{
ctCell.CssClass = "tcmixtext";
}
//lnkevent.Attributes.Add("onClick", "test();");
//lnkevent.Click += lnkevent_OnClick;
lnkevent.Click += new EventHandler(lnkevent_OnClick);
ctCell.Controls.Add(lnkevent);
}
tr.Cells.Add(ctCell);
}
tblcalendar.Rows.Add(tr);
}
}
}
public void lnkevent_OnClick(object sender,EventArgs e)
{
lblmonthname.Text = "hellooo";
txttitle.Text = "";
}
Sounds like you are adding a button, but not binding an event listener to it. I don't know much about how asp.net does event binding, but it sounds like that could be your problem.
Maybe this link can help?
asp.net dynamically button with event handler
How to display multiple icons on same points in googlemap in .net using goolemap api 3
Below is my code
public void selectTrainings(string strQuery)
{
try
{
clsTblMembers objtblMember = new clsTblMembers();
objtblMember.StrEmail = strQuery.ToString();
DataTable dt = objtblMember.SelectSearch();
if (dt != null)
{
int i;
for (i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["Latitude"].ToString() != "" && dt.Rows[i]["Longitude"].ToString() != "")
{
string StrLat = dt.Rows[i]["Latitude"].ToString();
string StrLon = dt.Rows[i]["Longitude"].ToString();
double Numlat;
bool isNumlat = double.TryParse(StrLat, out Numlat);
double Numlon;
bool isNumlon = double.TryParse(StrLon, out Numlon);
if ((isNumlat) && (isNumlon))
{
//coordinates datatype =double;
m1 = new MapControl.MapMarker();
m1.Latitude = Convert.ToDouble(dt.Rows[i]["Latitude"].ToString());
m1.Longitude = Convert.ToDouble(dt.Rows[i]["Longitude"].ToString());
getTraining(Convert.ToInt32(dt.Rows[i]["intId"].ToString()), Convert.ToInt32(dt.Rows[i]["intTypeId"].ToString()), dt.Rows[i]["strCode"].ToString(), dt.Rows[i]["strConductedBy"].ToString(), dt.Rows[i]["dtFromDate"].ToString(), dt.Rows[i]["dtToDate"].ToString(), dt.Rows[i]["strName"].ToString(), dt.Rows[i]["strUC"].ToString(), dt.Rows[i]["strVillage"].ToString());
if (dt.Rows[i]["intTypeId"].ToString() == "1")
{
m1.Title ="CMST - "+ dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t1.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "2")
{
m1.Title = "LMST - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t2.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "3")
{
m1.Title = " Govt.Official Training - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t3.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "4")
{
m1.Title = "Gender Based Violence - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/pg.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "5")
{
m1.Title = "Human Rights - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/ph.png";
}
else
{
m1.Title = "Livelihoods Skills Training - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t4.png";
}
m1.ImageSize1 = 32.0;
m1.ImageSize2 = 37.0;
m1.ImagePoint1 = 0;
m1.ImagePoint2 = 0;
m1.ImagePoint3 = 16.0;
m1.ImagePoint4 = 18.0;
m1.Shadow = "mapIcons/shadow.png";
m1.ShadowSize1 = 51.0;
m1.ShadowSize2 = 37.0;
m1.ShadowPoint1 = 0;
m1.ShadowPoint2 = 0;
m1.ShadowPoint3 = 16.0;
m1.ShadowPoint4 = 18.0;
GoogleMap.Markers.Add(m1);
}
}
}
}
}
catch (Exception ex)
{
}
}