I want to display time in textbox or in something like a numericupdownextender used in AJAX so that the user can change time as he desires..
i have used the control to show numbers and increase accordingly..
is there a way to do this..
new code but not what is desired...
<asp:TextBox runat="server" ID="txtHour"></asp:TextBox>
<ajaxToolkit:NumericUpDownExtender ID="txtHour_NumericUpDownExtender" runat="server" Enabled="True" Maximum="12" Minimum="1" TargetControlID="txtHour" Width="70"></ajaxToolkit:NumericUpDownExtender>
<asp:TextBox runat="server" ID="txtMinute"></asp:TextBox>
<ajaxToolkit:NumericUpDownExtender ID="txtMinute_NumericUpDownExtender" runat="server" Enabled="True" Maximum="60" Minimum="1" TargetControlID="txtMinute" Width="70"></ajaxToolkit:NumericUpDownExtender>
<asp:TextBox runat="server" ID="txtDayPart"></asp:TextBox>
<ajaxToolkit:NumericUpDownExtender ID="txtDayPart_NumericUpDownExtender" runat="server" Enabled="True" RefValues="AM;PM" TargetControlID="txtDayPart" Width="70"></ajaxToolkit:NumericUpDownExtender>
the code behind is:
private void ParseTime(string TimeString)
{
// Validation of input
if (TimeString.IndexOf(":") == -1)
{
return;
}
if ((TimeString.IndexOf("PM") == -1) && (TimeString.IndexOf("AM") == -1))
{
return;
}
// Good to go with format
int ColonPos = TimeString.IndexOf(":");
int AMPos = TimeString.IndexOf("AM");
int PMPos = TimeString.IndexOf("PM");
string sHour = TimeString.Substring(0, ColonPos);
string sMinutes = TimeString.Substring(ColonPos, 3); string sDayPart = (TimeString.IndexOf("AM") != -1) ? TimeString.Substring(AMPos, 2) : TimeString.Substring(PMPos, 2);
txtHour.Text = sHour;
txtMinute.Text = sMinutes;
txtDayPart.Text = sDayPart;
}
Yes this should be pretty simple to achieve using the updownextender. Just attach web service methods to the serviceupmethod and servicedownmethod which increment/decrement your datetime by the required timespan. you haven't posted any code so it's difficult to know where you are stuck.
UPDATE: ok, so having thought about this, I don't think there is any real reason to use an updownextender with server call backs. A quick google discovered that javascript already has some basic date manipulation functions, so it's easy enough to do everything client side.
I'm not a javascript expert, so the following code is possibly of questionable quality, but it seems to work ok and hopefully will get you set on the right track. Let me know if you still get stuck.
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
<!--
var date;
function initDateObject()
{
date = new Date ( "January 1, 2000 12:00:00" );
showTimePortion();
}
function showTimePortion()
{
document.getElementById('timeDisplay').value = padToMinimumLength(date.getHours(),2) + ':' + padToMinimumLength(date.getMinutes(),2) + ':' + padToMinimumLength(date.getSeconds(),2);
}
function padToMinimumLength(number, requiredLength)
{
var pads = requiredLength - (number + '').length;
while (pads > 0)
{
number = '0' + number;
pads--;
}
return number;
}
function addMinutes(n)
{
date.setMinutes(date.getMinutes() + n);
showTimePortion();
}
function setTodaysTime()
{
var d = new Date();
d.setHours(date.getHours());
d.setMinutes(date.getMinutes());
d.setSeconds(date.getSeconds());
alert('the time is now ' + d.toString());
}
-->
</script>
</head>
<body onload="initDateObject();">
<form id="form1" runat="server">
<div>
<input type="text" id="timeDisplay" readonly="readonly"/>
+
-
<br />
Submit
</div>
</form>
</body>
Hrmm, I recommend you spend some time playing around with jQuery if you haven't. Hope it helps.
jQuery UI
John Resig
lovemore-world has a good article that hopefuly can inspire you and get the creative juices going.
Related
Hi is it possible to change the error message of a asp.net range validator based on the value of the textbox. For example if the number is below 0, display the error message, "number can not be less than 0" and if it is above the max value set the error message to "number can't be above maxvalue".
if (stockCount < Convert.ToInt32(range.MinimumValue))
{
range.ErrorMessage = "Quantity has to be minumm of 1";
}
else if (stockCount > Convert.ToInt32(range.MaximumValue))
{
range.ErrorMessage = "Not enough items in stock";
}
this is the code which i have had no success with, any suggestions or advice is more than appreciated.
You can use a simple jQuery listener on the TextBox and change the error message based on it's input.
<script type="text/javascript">
$('#<%= TextBox1.ClientID %>').keyup(function () {
var validator = document.getElementById('<%= RangeValidator1.ClientID %>');
var errorMsg = 'Your value of ' + $(this).val() + ' is incorrect (max is ' + validator.maximumvalue + ')';
$('#<%= RangeValidator1.ClientID %>').text(errorMsg);
});
</script>
If you want in ASP.NET and C# only try below way of doing:
Declare a rangevalidator for your text box
<asp:TextBox id="text1" runat="server"></asp:TextBox><br />
<asp:RangeValidator EnableClientScript="false"
id="RangeValidator1"
runat="server"
ControlToValidate="text1" >
</asp:RangeValidator>
You have to invoke Validate() function of RangeValidator.
And in your code, try below pseudo code where ever you want to validate. (Not tested)
RangeValidator1.MinimumValue = 0;
RangeValidator1.MaximumValue = 10;
RangeValidator1.Type = ValidationDataType.Integer;
RangeValidator1.Validate();
if (!RangeValidator1.IsValid)
{
if(Convert.ToInt32(text1.Text) < 0)
{
RangeValidator1.ErrorMessage = "number can not be less than 0";
}
else
{
RangeValidator1.ErrorMessage = "number can't be above maxvalue";
}
}
Maybe my answer didn't show two different messages, but i think it simpler and cleaner to summarized the message in one error message.
you can use Class and put Range validator with error message on top.
I am very sorry if my suggestion is not to your liking.
public class Example
{
[Range(10, 1000, ErrorMessage = "Value must be between {1} and {2}.")]
public int Quantity { get; set; }
....
}
I'm using the FlickrNet c# library that so far is proving a massive hit.
However, I've got one problem. I can get all photos for a user id but I can't get the set name that a specific photo belongs to without doing another api call. This separate call is giving me massive performance issues. The homepage takes 30 seconds to load 40 images. This will only increase.
I need to get the set name for each photo as I'm using isotope to display the images.
I'm simply grabbing the images from the api and binding them to a repeater.
Here's my code.
C#
Flickr f = FlickrManager.GetAuthInstance();
protected void Page_Load(object sender, EventArgs e)
{
string userID = f.PeopleFindByEmail("me#yahoo.com").UserId;
PhotoSearchOptions options = new PhotoSearchOptions
{
UserId = userID,
Extras = PhotoSearchExtras.AllUrls | PhotoSearchExtras.Description | PhotoSearchExtras.Tags,
SortOrder = PhotoSearchSortOrder.Relevance,
};
var photos = f.PhotosSearch(options);
rptPhotos.DataSource = photos;
rptPhotos.DataBind();
}
protected string GetSetNameForImageID(string imageID)
{
var sets = f.PhotosGetAllContexts(imageID).Sets;
return sets[0].Title.ToLower().Replace(" ", "-");
}
HTML
<asp:Repeater runat="server" ID="rptPhotos">
<ItemTemplate>
<section class="<%# GetSetNameForImageID( Convert.ToString( Eval("PhotoID") ) ) %> item">
<%--<a href="#Url.Action("Image", "Home", new {id = item.PhotoId})">--%>
<a href="/View.aspx?pid=<%# DataBinder.Eval(Container.DataItem, "PhotoID") %>">
<div>
<div class="item_hover">
<header>
<span>D</span>
<%--<p title="#item.Description" class="tiptip">_</p> --%>
<p title="<%# DataBinder.Eval(Container.DataItem, "Description") %>" class="tiptip">_</p>
<hgroup>
<%--<h2>#item.Title</h2>
<h3>#item.Tags[0]</h3>--%>
<h2><%# DataBinder.Eval(Container.DataItem, "Title") %></h2>
<h3><%# DataBinder.Eval(Container.DataItem, "Tags[0]") %></h3>
</hgroup>
</header>
</div>
<%--<img src="#item.Small320Url" alt="Video sit amet consectetur" />--%>
<img src="<%# DataBinder.Eval(Container.DataItem, "Small320Url") %>" alt="Video sit amet consectetur" />
</div>
</a>
</section>
</ItemTemplate>
</asp:Repeater>
Is there a quicker way of getting the set name for each image without the GetSetNameForImageID and subsequent api call?
One thing I noticed about the PhotosGetAllContexts is that the Sets property you are using is a collection of ContextSet objects, which in turn store a PhotoSetId and a Title.
What about combining the PhotosetsGetList and PhotosetsGetPhotos methods? I think you could use these two to avoid the overhead you are currently experiencing with the PhotosGetAllContexts method.
Disclaimer: not tested code.
var photoSets = f.PhotosetsGetList(userId);
Dictionary<string, List<Photo>> photoSetPhotoMap = new Dictionary<string, List<Photo>>();
foreach (var photoSet in photoSets)
{
var photoSetPhotos = f.PhotosetsGetPhotos(photoSet.PhotosetId,
PhotoSearchExtras.AllUrls | PhotoSearchExtras.Description | PhotoSearchExtras.Tags);
photoSetPhotoMap.Add(photoSet.PhotosetId, photoSetPhotos.ToList());
}
var photos =
from kvp in photoSetPhotoMap
from photo in kvp.Value
select new
{
SetTitle = kvp.Key, PhotoId = photo.PhotoId, Description = photo.Description,
PhotoTitle = photo.Title, Tags = photo.Tags[0], Small320Url = photo.Small320Url
};
rptPhotos.DataSource = photos;
rptPhotos.DataBind();
I think the main difficulty you will have with this approach is implementing paging effectively - depending on the size of a photoset (you can determine this by the NumberOfPhotos property) you will likely run across scenarios where a page cuts off halfway through a photoset.
To solve this I would suggest using the NumberOfPhotos property to calculate the total number of photos and then using your page size multiplied by the page number to figure out how many and which PhotoSets you need to get to fulfill the request.
I am working on a donations website. In my page, I have a textbox which accepts a numeric value from the user (that is, money to be donated).
In my code-behind, I have a method which checks whether the value in the textbox is numeric. The method generates an error message if the number is invalid.
I also have a JavaScript which, after checking that the value in the textbox is numeric, opens a new tab to the website confirmation page, thanking the user for his donation. Here is the code of the javascript:
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('DonationTextBox');
if (textbox.value != "")
{
if (isNan(textbox) == false)
{
window.open("DonationConfirmation.aspx")
}
}
}
</script>
The problem is that the tab is NEVER opened, even if the number is valid. Can you please help me solve this problem? Thank you.
P.S.
Here is the code of the button that initiates the validation:
<asp:ImageButton ID="PayPalButton2" runat="server" ImageAlign="Middle"
ImageUrl="Resources/Icons/PayPalCheckOut.gif"
onclick="PayPalButton2_Click" OnClientClick="Open_Window()"/>
The function name is isNaN. Note: The final 'N' is capital. That should solve your problem.
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('<%=DonationTextBox.ClientID%>');
if (textbox.value != "" && !isNaN(textbox.value)) {
window.open("DonationConfirmation.aspx");
}
}
</script>
edit
instead of isNan should be isNaN (javascript is casesensitive)
Shouldn't this line...
if (isNan(textbox) == false)
be this instead...
if (isNan(textbox.value) == false)
First, I would recommend explicitly parsing the number, not relying on the implicit ToNumber operation that will be applied when you pass a string into isNaN. Presumably your users are inputting decimal, so if it's meant to be a whole number (e.g., 10), use:
var num = parseInt(textbox.value, 10);
If it's meant to be a number with a fractional component (e.g., 10.5), use:
var num = parseFloat(textbox.value);
You probably want parseFloat for a currency value.
Then your if condition becomes isNaN (note that the final N is capped) on num:
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('DonationTextBox');
var num = parseInt(textbox.value, 10);
if (!isNaN(num))
{
window.open("DonationConfirmation.aspx")
}
}
</script>
And lastly, are you sure that the client-side ID of the textbox really is 'DonationTextBox'? ASP auto-generates client-side IDs, you may need to use ClientID instead, e.g.:
var textbox = document.getElementById('<%=DonationTextBox.ClientID%>');
Here is a stripped down working jsFiddle example:
http://jsfiddle.net/pjgalbraith/QZeSF/
The html:
Open
<textarea id="donationTextBox">1</textarea>
And the js:
function openWindow() {
if($('#donationTextBox').val() && isNaN($('#donationTextBox').val()) === false)
window.open("http://www.google.com/", "mywindow");
}
$(document).ready(function() {
$('#PayPalButton2').click(function(){
openWindow();
});
});
I am attempting to fill in an ASP.NET page textbox with some predefined text so that when it is displayed the value is predefined. I have tried
protected void Page_PreRender ()
{
mytextbox.Text = somestring;
}
which works fine in the development environment but on the server produces...
System.NullReferenceException: Object reference not set to an instance of an object
The same applies when I try this in Page_Load. As I read the answers to this question, what I am trying should work (in at least one of these places).
Can anyone see what I am doing wrong?
EDIT more code, as suggested. The C# looks like this:-
protected void Page_PreRender (Object sender, EventArgs e)
{
try
{
string [] file_list;
int i = 0;
file_list = Directory.GetFiles(MyProg.Common.GetDirectory(),
MyProg.Common.GetFileNameRoot() + "*.*");
foreach (string filename in file_list)
{
string filenameonly = Path.GetFileName (filename);
if (filenameonly == MyProg.Common.GetFileNameRoot() + "runlog.log")
{
nametextbox.Text = filenameonly;
}
}
}
catch (Exception ex)
{
string mystring = ex.ToString();
errorMessage.Text = "Page Load Error : " + mystring;
}
}
and the ASP.NET page like this...
<%# Page Language="C#"
AutoEventWireup="true"
CodeBehind="MyDialogue.aspx.cs"
Inherits="MyDialogue" %>
<%# Register assembly="ComponentArt.Web.UI"
namespace="ComponentArt.Web.UI"
tagprefix="ComponentArt" %>
<%# Register assembly="ComponentArt.Web.Visualization.Charting"
namespace="ComponentArt.Web.Visualization.Charting"
tagprefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
</head>
<body>
<form id="myForm" runat="server">
<div style="visibility:hidden">
<asp:TextBox ID="nametextbox"
TextMode="MultiLine"
runat="server"
Visible="true" />
</div>
</form>
</body>
</html>
Did you publish your site but did the filerefence to the codebehind stay in the aspx page?
are you sure the dll in the bin folder?
This should work without complaint. Does the mytextbox control have the runat="server" attribute? You can only access from the codebehind stuff with the runat="server" attribute.
There could be several areas that are causing this problem. How are you sure that you've narrowed it down to the textbox itself? Was this code completely bug-free before adding the textbox message? I'll post your code below with where I think potential null references may be occurring (in comments):
string [] file_list;
int i = 0;
file_list = Directory.GetFiles(MyProg.Common.GetDirectory(),
MyProg.Common.GetFileNameRoot() + "*.*");
// it is possible that file_list is null
// potentially due to an invalid path (missing / perhaps?)
foreach (string filename in file_list)
{
string filenameonly = Path.GetFileName (filename);
// It's possible that the MixedZone.Kernel.Common library
// is experiencing the null reference exception because it
// may not understand what file to get the name root of or
// maybe it is not capable of getting the root for some
// other reason (permissions perhaps?)
if (filenameonly == MixedZone.Kernel.Common.GetFileNameRoot() + "runlog.log")
{
nametextbox.Text = filenameonly;
}
Some possible solutions or safer code:
string [] file_list;
int i = 0;
file_list = Directory.GetFiles(MyProg.Common.GetDirectory(),
MyProg.Common.GetFileNameRoot() + "*.*");
if (file_list == null) throw new Exception("File List is null. Something is wrong.");
foreach (string filename in file_list)
{
string filenameonly = Path.GetFileName (filename);
string fileroot = MixedZone.Kernel.Common.GetFileNameRoot();
if(string.IsNullOrEmpty(fileroot) throw new Exception("MixedZone Library failed.");
if (filenameonly.Equals(fileroot + "runlog.log", StringComparison.OrdinalIgnoreCase)) // Choose your own string comparison here
{
nametextbox.Text = filenameonly;
}
Run with Antivirus disabled on the Production Server?
Compare .Net versions between Production and Development?
"which works fine in the development environment but on the server produces" - so, permissions or missing files perhaps?
I've got a simple spam killer I'm trying to put together, but the text is not showing up on my form.
The javascript is:
<script language="javascript" type="text/javascript">
document.write("SPAM Killer: What is " + GetDateMonth() + " + " + GetDateDay() + "?")
</script>
In my .js file, I have these two functions defined:
function GetDateMonth() {
return date1.getMonth() + 1;
}
function GetDateDay() {
return date1.getDay() + 1;
}
The text shows up under IE8, but not under Chrome.
As a bonus: My OnClick method of my Submit form has this bit of code that is incorrectly adding my month and date:
string spamError = "The SPAM Killer answer was incorrect. ";
char[] split = spamTest.ToCharArray();
for (int i = 0; i < split.Length; i++) {
if (char.IsLetter(split[i])) {
Ok = false;
txtMessage.Text = spamError + "Non-numeric data entered.";
return;
}
}
int nTestValue = Convert.ToInt32(spamTest, 10);
if (nTestValue < 1) {
Ok = false;
txtMessage.Text = spamError + "Negatave or zero value found.";
}
DateTime dt = DateTime.Now;
int month = dt.Month;
int day = dt.Day;
int nCorrect = month + day;
if (nCorrect != nTestValue) {
Ok = false;
txtMessage.Text = spamError + string.Format("Expected {0}; Received {1}.", nCorrect, nTestValue);
return;
}
Using IE8, I see the following:
SPAM Killer: What is 2 + 3?
I enter 5, click Send, and get Expected 17; Received 5.
Don't reinvent the wheel, help read books with http://www.google.com/recaptcha
For C# code see http://code.google.com/apis/recaptcha/docs/aspnet.html
If you're adamant on sticking with your code, think about the problems around midnight, and users in other timezones. Also, a bot can very easily answer your anti-bot question, it would take me 45 seconds to code support for that, if I wrote bots.
If you're still adamant, you shouldn't use document.write anymore (not since 2002), but instead use DOM to insert the text to a tag ID like this: Change label text using Javascript
The answer, it seems, was in using the document.write() function with appending strings.
I redesigned my HTML to be more like this:
<table>
<tr>
<td colspan="2">
<b>[Human Check]</b><br />
Enter the text to the left and below exactly as it appears:
</td>
</tr>
<tr>
<td>
<script language="javascript" type="text/javascript">
document.write(GetSpamText())
</script>
</td>
</tr>
</table>
#serverfault: Thanks for your suggestion about the date property, though. That would have been a problem.
The text returned by GetSpamText() can be static or coded to create a random value (another topic).