Converted string not in correct format - visual-studio-2010

First of all, I am aware that there's numerous questions like mine, but after analyzing them, I get an idea of what to do, but ultimately keep getting errors.
I'm using visual studio 2012 and c++ language to create a time card windows form as shown below.
http://i1294.photobucket.com/albums/b618/uRsh3RRaYm0nD/checkin_zpsa4ccebda.jpg
As you can see, I was able to convert and calculate the datetimepicker range values to string in order to show those values underneath the Hours text box.
Where I'm having trouble is coding the Total Hours Get button that will subtract both Hour's text boxes, in order to display them in the Total Hours text box.
I've tried converting those string values back to DateTime, performing the calculation, and then converting the result to string to display it.
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
if( this->dtpMondayIn->Value > this->dtpMondayOut->Value )
this->dtpMondayIn->Value = this->dtpMondayOut->Value;
System::TimeSpan diff = this->dtpMondayOut->Value.Subtract(this->dtpMondayIn->Value);
txtMonday->Text = Convert::ToString(diff);
}
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) {
if(this->dtpLunchIn->Value > this->dtpLunchOut->Value)
this->dtpLunchIn->Value = this->dtpLunchOut->Value;
System::TimeSpan diff2 = this->dtpLunchOut->Value.Subtract(this->dtpLunchIn->Value);
txtLunch->Text = Convert::ToString(diff2);
}
private: System::Void get1_Click(System::Object^ sender, System::EventArgs^ e) {
DateTime lunch, work, total;
lunch = Convert::ToDateTime(txtLunch->Text);
work = Convert::ToDateTime(txtLunch->Text);
total = lunch - work;
txtTotalHours->Text = Convert::ToString(total);
//This is where I get the error error C2440: '=' : cannot convert from 'System::TimeSpan' to 'System::DateTime

Use TimeSpan to calculate durations. DateTime does what it says on the tin, it represents a moment in time.
private: System::Void get1_Click(System::Object^ sender, System::EventArgs^ e)
{
TimeSpan work, lunch, total;
work = this->dtpMondayOut->Value.Subtract(this->dtpMondayIn->Value);
lunch = this->dtpLunchOut->Value.Subtract(this->dtpLunchIn->Value);
total = lunch - work;
txtTotalHours->Text = Convert.ToDecimal(total->TotalHours).ToString("#.00");
}
Edit: Changed txtTotalHours output to match decimal output of provided image.

Related

Xamarin.Forms Entry with auto thousand and decimal separator

I have a Xamarin.Forms entry with numeric keyboard that will represent a pt-BR REAL currency (999.999,99). When I type numbers in the numeric keyboard, the comma(representing decimal) and dot(representind thousand) needs to be added automatically while I am typing.
To achieve this goal, what is the best practice/design pattern in Xamarin.Forms to work in all platforms?
The trick is to use a TextChanged event. The first step I removed the $ from the string so that I could parse the new text value. If it fails to parse, that means that the user added a non-digit character and we just revert to whatever the old text was.
Next, we detect if user ADDED a new digit and its to the RIGHT of the decimal (example 1.532). If so we, we move the decimal to the right by * 10. Do the opposite for a DELETION.
OH, and almost forgot about when we initialize the number! The first digit we enter will be a whole number so we * 100 to make sure the first digit we enter starts as fraction.
Once we got our decimal correct, we display it using num.ToString("C");
Working Example:
xaml:
<Entry
Keyboard="Numeric"
TextChanged="OnFinancialTextChanged"
Placeholder="$10.00"
Text="{Binding RetailPrice}"/>
Then in the cs
.cs:
private void OnFinancialTextChanged(object sender, TextChangedEventArgs e)
{
var entry = (Entry)sender;
var amt = e.NewTextValue.Replace("$", "");
if (decimal.TryParse(amt, out decimal num))
{
// Init our number
if(string.IsNullOrEmpty(e.OldTextValue))
{
num = num / 100;
}
// Shift decimal to right if added a decimal digit
else if (num.DecimalDigits() > 2 && !e.IsDeletion())
{
num = num * 10;
}
// Shift decimal to left if deleted a decimal digit
else if(num.DecimalDigits() < 2 && e.IsDeletion())
{
num = num / 10;
}
entry.Text = num.ToString("C");
}
else
{
entry.Text = e.OldTextValue;
}
}
I created these Extension methods to help with the logic
public static class ExtensionMethods
{
public static int DecimalDigits(this decimal n)
{
return n.ToString(System.Globalization.CultureInfo.InvariantCulture)
.SkipWhile(c => c != '.')
.Skip(1)
.Count();
}
public static bool IsDeletion(this TextChangedEventArgs e)
{
return !string.IsNullOrEmpty(e.OldTextValue) && e.OldTextValue.Length > e.NewTextValue.Length;
}
}
No need to create a custom renderer.
I recommend to subclass Entry and subscribe to the TextChanged event.
In there you would parse and reformat the current text and update the Text property.

xamarin convert entry text to numeric value

I'm new user of Xamarin studio 5.9.5 (build 9) on Windows, and I want make a form based application that involves some mathematical calculations (.Net + Gtk#).
I made a simple form containing 3 Entry widgets (2 for input values and 1 for output value) and 1 button. Here is the code for the button (simple addition Entry3 = Entry1 + Entry2)
using System;
using Gtk;
...
protected void OnBtnClicked (object sender, EventArgs e)
{
entry3.Text = entry1.Text + entry2.Text;
//throw new NotImplementedException ();
}
As you can see, this code just makes a concatenation of both text fields.
How can I convert the text fields into numeric values in order to achieve mathematical addition (and other calculations) ?
Thanks
// assuming these values are ints
int val1 = int.Parse(entry1.Text);
int val2 = int.Parse(entry2.Text);
entry3.Text = val1 + val2;

Easiest way to get time between TouchesMoved method calls

I've been searching for easy way to get time step between TouchedMoved method calls in cocos2d-x, but so far I find nothing.. Could you help me out here?
You can accomplish it directly with the C++ primitives, follow this link:
http://www.cplusplus.com/reference/ctime/time/
You'll find a sample script which demonstrates how to calculate difference between two times.
Another way is to sum the delta time of the update method into an instance var, like this:
void YourClass::update(float dt)
{
m_timer += dt;
}
Then in your onTouchBegin, onTouchMoved and onTouchEnded methods get the value of m_timer and count the difference. For example:
void YourClass::onTouchBegin(cocos2d::Touch *touch, cocos2d::Event *event) {
float m_beginTime = m_timer;
}
void YourClass::onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *event) {
float m_endTime = m_timer;
float time_diff = m_endTime - m_beginTime;
}

How To Get A Random Number To Count Down

I am trying to get a random number to count down to zero, but what i have keeps giving me a random number. Then every second it will generate a new random number between 4 and 11, and won't count down. if anyone can help it would be greatly appreciated. thanks in advance!
enter code here
private void timer1_Tick(object sender, EventArgs e)
{
Random nuber = new Random();
i = nuber.Next(4, 11);
i--;
textBox1.Text = i.ToString();
if(i == 0)
{
Form1 f1 = new Form1();
Form2 f2 = new Form2();
f2.Show();
f1.Close();
}
}
If I understand what you are trying to do, then you need to generate the number outside of the loop, in an initialization phase, in a static (global) variable. Then the timer tick will count it down. Note your f1 is created and then closed, it never shows, so is superfluous. Also you are creating a new form every time which is maybe not what you want.
Basically you need to move just the two statements:
random nuber = new Random();
i = number.next();
to wherever it is that you create the timer.

JFreeChart Performance

I'm trying to plot some graphs simultaneously:
Each representing an attribute and displays the results for several objects each containing its own data items series.
I encounter very bad performance using either add(...) or addOrUpdate(...) methods of the TimeSeries - time for plotting ~16,000 items is about 60 seconds.
I read about the performance issue - http://www.jfree.org/phpBB2/viewtopic.php?t=12130&start=0 - but it seems to me like it is much worse in my case for some reason.
I'd like to understand whether this is truly the performance that I may squeeze out of the module (2.5GHz machine running windows - I doubt that).
How can I get my application accelerated with this respect?
Here is a basic version of the code (note that it is all done in a dedicated thread):
/* attribute -> (Object -> graph values) */
protected HashMap<String,HashMap<Object,Vector<TimeSeriesDataItem>>> m_data =
new HashMap<String,HashMap<Object,Vector<TimeSeriesDataItem>>>();
public void loadGraph() {
int items = 0;
for (String attr : m_data.keySet())
for (Object obj : m_data.get(attr).keySet())
for (TimeSeriesDataItem dataItem : m_data.get(attr).get(obj))
items++;
long before = System.currentTimeMillis();
// plot each graph
for (String attr : m_data.keySet()) {
GraphXYPlot plot = m_plots.get(attr);
plot.addToObservation(m_data.get(attr));
}
System.err.printf("Time for plotting %d items is: %d ms", items, System.currentTimeMillis()-before);
// => Time for plotting 16540 items is: 59910 ms
}
public void addToObservation(HashMap<Object, Vector<TimeSeriesDataItem>> plotData) {
for (Object obj : plotData.keySet()) {
SeriesHandler handler = m_series.get(obj);
if (handler != null) {
TimeSeries fullSeries = handler.getFullSeries();
TimeSeries periodSeries = handler.getPeriodseries();
for (TimeSeriesDataItem dataItem : plotData.get(obj)) {
fullSeries.add(dataItem);
periodSeries.add(dataItem);
}
}
}
}
Thanks a lot !
Guy
Absent more details, any of several general optimizations should be considered:
Invoke setNotify(false), as suggested here.
Cache already calculated values, as discussed here.
Adopt a paging strategy, as shown here.
Chart a summary of average/time-unit values; based on the ChartEntity seen in a ChartMouseListener, show an expanded subset in an adjacent panel.

Resources