Fixed DataStringFormat GirdView - asp.net

Is there a way how to format a number in gridview with fixed currency format? I use
DataFormatString="{0:C}"
but since my page is available in multiple languages it also changes currency signs. Is there a way how to apply format to column like this?
"C0",CultureInfo.CreateSpecificCulture('en-US')

Yes, change the data format by transform when get the data, no when show them. If you parse the data to string in the format that you want you don't need to transform in the server. For example if you are using sql server you can format by the view.
If this is noy what you expect write me in a comment.
Thanks

You can overwrite the Culture for that page and even define a custom currency symbol if needed.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US")
{
NumberFormat = { CurrencySymbol = "%" }
};

For those who will need something similar there is a solution
protected void grdReport_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
Decimal dec;
if (Decimal.TryParse(e.Row.Cells[1].Text, out dec))
e.Row.Cells[1].Text = dec.ToString("C0", CultureInfo.CreateSpecificCulture("cs-CZ"));
}
I need only display those number so this is ok for me. In case you need to work with them you need to split the text and then convert it to number.

Related

Binding time values to asp.net GridView

I need to bind time values to my gridview. For example, if the time is 13:00, I need to display it as 13-00 in the grid. But it displays as 01-00. How do I resolve this?
You can use GridView.RowDataBound Event to achieve it. Format your time string as you want and assign to to the grid view cell.
You can use date formats to convert datetime into 24-hrs format.
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Text = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
}
}
You need to convert the value into 24-hour format (for instance by selecting a different culture for your application) or simply create some converter class that will convert this for you. There are multiple resources to learn from.
Something like this should work:
DateTime localTime = DateTime.Now;
// 24 hour format -- use 'H' or 'HH'
string timeString24Hour = localTime.ToString("HH:mm", CultureInfo.CurrentCulture);
Taken from another answer here in SO Convert AM/PM time to 24 hours format?
If your culture uses 12-hour format, use a different culture info for the parsing that supports 24-hour format.
Of course you'd probably like to wrap this in a getter property so it will be available for the binding
public string DateIn24HourFormat
{
get
{
return MyConvertFunction(this.Time);
}
}
You get the idea.
Give your Time format in DataFormatString property in BoundColumn.
Apply format as
{0:HH-mm}
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring.aspx

ASP Multiselect listbox separator

I have encountered a problem and I didn't manage to find any soultions yet. Let me simplify things a bit.
I have 2 forms, the first contains an ASP ListBox with multi select mode enabled. I submit the form and in the other form I use just for testing purposes this snippet of code:
protected void Page_Load(object sender, EventArgs e)
{
foreach (string formKey in Request.Form.AllKeys)
{
if (formKey != null)
{
if (formKey.Equals("ctl00$MainContent$ListBox1"))
Label1.Text = Request.Form[formKey];
}
}
}
The problems is that the values that come from the listbox (the values that i selected in the previous form) are separated by "," for ex. "test1,test2,test3". How can i change this separator to "$" for example? I need to change it because the actual values may contain "," and i don't manualy feed them to the listbox.
I can't use any other mode of transfering this values between the form because the entire application uses this model. The values that i get are then sent to a workflow where there will be manipulated and in the workflow i need to know where each listbox item starts and ends so it must be an unique separator.
Any help is apreciated! Thank you very much
Thank you MatteKarla but unfortunately this does not solve my problem. Yes, this is a good way of transfering the values from one form to another.
However i must use the method I described above with Request form keys because the listbox is one of many others "parameters" that are generated at runtime and have their values sent to a workflow method that takes this values. And i can't afford to change that in my application.
My problem is that coma (",") separator is used by default with a multiselect listbox.
I thought that there maybe is a method to change that separator from coma to another char because the coma can also be included in the value itself and this will create confusion.
As i said if i select three values test1, test2 and test3, the result with my method will be a string looking like "test1,test2,test3". However a "test1$test2$test3" would be much better.
But I'm affraid that changing this default separator is not possbile. I must think at a method to overcome this problem like replacing before feeding the listbox all the intended coma from the values with some other char not to create confusion. But this is not a great way of doing it.
On your first page/form (First.aspx.cs) create a public property with the listbox:
public ListBox PostedListBox { get { return ListBox1; } }
Set the postback-url for the button to Second.aspx
Second page in the aspx-file after the #Page-directive add:
<%# PreviousPageType VirtualPath="~/First.aspx" %>
Then in Form_Load on Second.aspx.cs you can extract the values:
if (PreviousPage != null)
{
ListBox postedListbox = PreviousPage.PostedListBox;
foreach (var index in postedListbox.GetSelectedIndices())
{
var itemText = postedListbox.Items[index].Text;
}
}
Or you could just try to locate the control by using:
if (PreviousPage != null)
{
var control = PreviousPage.FindControl("ListBox1") as ListBox;
}
Third Edit:
You could use GetValues:
Request.Form.GetValues("ctl00$MainContent$ListBox1");
returns a string array containing each of the selected items.

Adobe Flex date

Hi I am having a problem in date.
I am having a custom dateChooser.
In the dateChooser component highlights some holidays and at the same time lists the holidays in a container.
The Problem is the date I am displaying in the container is not in ascending order could some one please help.
Link for the demo application with view source enabled
http://125.22.254.206/clients/flexdemos/calendardemo/calendardemo.html
The said logic is implemented in ExtendedDateChooser.as under custome folder.
Are you trying to sort the date in the 'holidayView' vbox?
You cant compare and sort two dates. You can use the date comparison method given below (search the web to find a better one).If the control in the vbox to display holidays is a datagrid, using
<mx:DataGridColumn
headerText="Created Date"
date="createdDt"
sortCompareFunction="date_sortCompareFunc">
</mx:DataGridColumn>
in the tag attribute will result in sortedDate
private function date_sortCompareFunc(itemA:Object, itemB:Object):int
{
/* Date.parse() returns an int, but
ObjectUtil.dateCompare() expects two
Date objects, so convert String to
int to Date. */
var dateA:Date=isoToDate(itemA.createdDt);
var dateB:Date=isoToDate(itemB.createdDt);
return ObjectUtil.dateCompare(dateB, dateA);
}
private function isoToDate(value:String):Date {
var dateStr:String = value;
dateStr = dateStr.replace(/\-/g, "/");
dateStr = dateStr.replace("T", " ");
dateStr = dateStr.replace("Z", " GMT-0000");
return new Date(Date.parse(dateStr));
}
I think, you cant sort by Date.
First, I can't see the container in your app.
My way would be to parse the date in to milliseconds since 1970
parse(date:String):Number
Then you can sort it by some logic.
BR
Frank

date validation

can any one tell me the code to validate the date field in signup form(which shd also validate the leap year and no of days in each month
That depends on the input but suppose you have a string input for the whole date then you could try something like:
try
{
DateTime parsedDate = DateTime.Parse(incomingDateString);
}
catch
{
throw new Exception("Incoming Date string could not be parsed as a DateTime");
}
Alternatively if you have three integers as strings coming in from the form then you would replace the DateTime.Parse with
DateTime parsedDate = new DateTime(Int32.Parse(yearString), Int32.Parse(MonthString), Int32.Parse(DayString));
and allow the DateTime constructor take care of the details of analyzing days of month and leap years. You could be more sophisticated and use Int32.TryParse and provide more specific error messages and checks for null strings if thats what you need.
You can make sure you get a valid date by adding a calendar control or a date picker control. This will avoid having to add extra validation just to validate this field.
If you don't want to use a calendar control or date picker, you can use DateTime.Parse and place it inside a Try, Catch block.
dateString = YourDateField.Text;
try {
dateValue = DateTime.Parse(dateString);
}
catch (FormatException) {
Console.WriteLine("Unable to convert, this is not a valid date '{0}'.", dateString);
}
Hope this helps.

Force ASP.NET textbox to display currency with $ sign

Is there a way to get an ASP.NET textbox to accept only currency values, and when the control is validated, insert a $ sign beforehand?
Examples:
10.23 becomes $10.23
$1.45 stays $1.45
10.a raises error due to not being a valid number
I have a RegularExpressionValidator that is verifying the number is valid, but I don't know how to force the $ sign into the text. I suspect JavaScript might work, but was wondering if there was another way to do this.
The ASP.NET MaskedEdit control from the AJAX Control Toolkit can accomplish what you're asking for.
I know an answer has already been accepted, but I wanted to throw out another solution for anyone with the same problem and looking for multiple workarounds.
The way I do this is to use jQuery format currency plugin to bind user input on the client side. Parsing this input on the server side only requires:
// directive
using System.Globalization;
// code
decimal input = -1;
if (decimal.TryParse(txtUserInput.Text, NumberStyles.Currency,
CultureInfo.InvariantCulture, out input))
{
parameter = input.ToString();
}
The only downfall to this is that the user can have javascript turned off, in which case the RegEx validator running server-side would work as a fall-back. If the control is databound, all you have to do is decimalValue.ToString("{0:c}") , as mentioned by others, in order to display the proper currency formatting.
The cool thing about this is that if the user enters the textbox and it shows $0.00 on the client side, the server-side if statement would return false. If your decimal value isn't nullable in the database, just change decimal input = -1 to decimal input = 0 and you'll have a default value of 0.
Another way to do this might be to place the dollar sign outside to the left of the text box. Is there a real need to have the dollar sign inside of the box or will a simple label do?
decimal sValue = decimal.Parse(txtboxValue.Text.Trim());
// Put Code to check whether the $ sign already exist or not.
//Try making a function returning boolean
//if Dollar sign not available do this
{ string LableText = string.Format("{0:c}", sValue); }
else
{ string LableText = Convert.ToString(sValue); }
string sValue = Convert.ToString(txtboxValue.Text.Trim());
// Put Code to check whether the $ sign already exist or not.
//Try making a function returning boolean
//if Dollar sign not available do this
{ string LableText = string.Format("{0:c}", "sValue"); }
else
{ string LableText = Convert.ToString(sValue); }
In the .CS you could do a pattern match along the lines of,
string value = text_box_to_validate.Text;
string myPattern = #"^\$(\d{1,3},?(\d{3},?)*\d{3}(\.\d{0,2})|\d{1,3}(\.\d{2})|\.\d{2})$";
Regex r = new Regex(myPattern);
Match m = r.Match(value);
if (m.Success)
{
//do something -- everything passed
}
else
{
//did not match
//could check if number is good, but is just missing $ in front
}

Resources