xamarin convert entry text to numeric value - xamarin

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;

Related

GTK# TreeView sorting and updating rows

I'm noob in GTK#, just making my first steps here..
Working now with TreeView GTK. Have already read this tutorial: https://www.mono-project.com/docs/gui/gtksharp/widgets/treeview-tutorial/
and make everything I need (adding data from my own class, column sorting with sorting functions)
But, according to the Title - I have 2 questions:
I need to refresh tree view with new data. And I don't want to "loose" scroll and selection. So the easiest way to clear liststore and fill with new data not works for me (I loose scroll). I need to update rows. I've already learned how to get values from TreeView.Model (iter as my class) - Question is how can I update Iters.
Is there any way to disable 3-d column sort position "default". When I click on column I can see Acc, Desc, modes and then some 3-d position (without sorting arrows). Now I make it in that way(remember sorting mode and column, and after refresh I selecting saved mode and column):
void Sortable_SortColumnChanged(object sender, EventArgs e)
{
int a;
SortType b;
sortable.GetSortColumnId(out a, out b);
if (a == -1)
{
if (default_sort_type == SortType.Ascending) default_sort_type = SortType.Descending;
else default_sort_type = SortType.Ascending;
sortable.SetSortColumnId(default_column, default_sort_type);
}
else
{
default_column = a;
default_sort_type = b;
}
}
But I think there is better way...

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.

How to get the XPath of a grid cell using Firebug?

I am working on a UI. My job is to automate it. I came across the following grid.
When you click on any cell under the Rule column, a browse button appears.
I am supposed to automate this scenario. So, using Firebug I am trying to extract the XPath of that cell.
I used Firebug's inspector to locate that particular cell, so that I can write the XPath for it, but I am unable to locate that cell. Instead, the entire row is getting selected, as shown in next images.
How should I approach this problem?
below code might help you to verify the grid values,
public void verifyTableValues(String expectedValue
) {
try {
//List of Fields values which you want to verify
List<String> expectedValues = Arrays.asList(expectedValue.split("#"));
// you will get the number of rows in Table Select the xpath to /tr
String tableRow = driver.findElements(By.xpath(//table row constant));
int tableRwCnt = getCount(tableRow);
// you will get the number of Columns in Table Select the xpath to /td
String tableColumn = driver.findElements(By.xpath(//table Column constant));
int tableColumnCnt = getCount(tableColumn);
for (int cnt = 1; cnt <= tableRwCnt; cnt++) {
for (int listCount = 1; listCount <= tableColumnCnt; listCount++) {
String actualVal = findElement(By.xpath(tableColumn + "[" + cnt + "]/td["
+ expectedValues.get(listCount) + "]").getText();
String expectdVal = expectedValues.get(listCount);
Assert.assertEquals("Value from table doent Match", expectdVal, actualVal);
}
}
} catch (Exception e) {
// code for exception
}
}
Parameter: expectedValue = test1#test2#test4#test4 (Grid values)

Table in Word looks different if halted on breakpoint

I have stumbled on a very annoying problem when setting column widths on a table in Word (using Microsoft Office 15.0 Object Library, VS 2013). If I run the code below without having any breakpoints, the result becomes incorrect (first column width should be 30%), but if I put a breakpoint (e.g.) on line 47, the generated Word file becomes as I want it to be.
The conclusion I make is that when the debugger stops execution, the given column size values are flushed into the data model and the output will be as I want it to be. Without the breakpoint, the merging of cells changes the widths (e.g. the first column becomes 12,5%).
I have searched for some sort of method/function to make the data model adjust to my programmatically given column sizes before the cell merging, with no luck. Anyone out there that can explain why halting on the breakpoint will change the output?
Regards,
Ola
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;
namespace ShowWordProblem
{
class Program
{
private const string WordFileName = #"C:\temp\test.doc";
static void Main(string[] args)
{
var wordApplication = new Application();
wordApplication.Visible = false;
var wordDocument = wordApplication.Documents.Add();
FillDocument(wordDocument);
wordDocument.SaveAs2(WordFileName);
wordDocument.Close();
wordApplication.Quit(Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(wordApplication);
wordApplication = null;
wordApplication = new Microsoft.Office.Interop.Word.Application();
wordApplication.Visible = true;
wordApplication.Documents.Open(WordFileName);
}
private static void FillDocument(Document wordDocument)
{
Range range = wordDocument.Content.Paragraphs.Add().Range;
var table = range.Tables.Add(range, 5, 8);
table.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPercent;
table.PreferredWidth = (float)100.0;
table.Columns.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPercent;
table.Columns.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPercent;
table.Columns[1].PreferredWidth = 30;
for (int i = 2; i <= 8; i++) table.Columns[i].PreferredWidth = 10;
var widths = table.Columns.OfType<Column>().Select(c => c.Width).ToArray();
MergeGroupHeaderCells(table.Rows[1], 5, 9);
MergeGroupHeaderCells(table.Rows[1], 2, 5);
}
private static void MergeGroupHeaderCells(Row row, int startIndex, int lastIndex)
{
var r = row.Cells[startIndex].Range;
Object cell = WdUnits.wdCell;
Object count = lastIndex - startIndex - 1;
r.MoveEnd(ref cell, ref count);
r.Cells.Merge();
}
}
}
Finally I found a way to force the code to apply the given percentage values to the columns before the merging of the cells, and thereby having the correct widths on all columns.
By adding the following line of code after the last PreferredWidth-assignment:
var info = table.Range.Information[WdInformation.wdWithInTable];
it seems that the given PreferredWidth values are propagated to the columns, and the final rendered word document looks exactly as I want it.
/Ola

How can i get the Text from Mouse Right Click?

I use Microsoft Visual Studio 2005. And try to programming with C#
I have a Textfile with Texts. For Example: D23423P 34L211 5 I copy this Text from the Textfile with Mouse Right Click Copy to use this for my 17 TextBoxs. The TextBoxs has the Label: label1.
So i created to label1 a ContextMenuStrip: Paste and Cut:
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
string tempr = Clipboard.GetText(TextDataFormat.Text);
textBox1.Paste(tempr);
}
If i click Paste the Function, i wanna get the Texts (D23423P 34L211 5 ) and fill the 17 TextBoxs for Example:
textBox1: D
textBox2: 2
textBox3: 4
....
I clicked Right Click "Paste" i save the Data text in tempr. How can i set the textBox 1 with D textbox 2 with 2...?
Should i use the Methode String split?
Declare a TextBox array in your class:
private const int TextBoxCount = 17;
private TextBox[] TextBoxArray;
And populate it somewhere in your form's constructor:
TextBoxArray = new TextBox[] { textBox1, textBox2, textBox3... };
In your paste function, loop through the string, and index with []:
for (int i = 0; i < TextBoxCount; i++)
TextBoxArray[i].Text = tempr[i];

Resources