Entry binded value is always 0 - xamarin.forms

I got my numeric entry binded to viewmodel's SelectedAmount. Nevertheless value is always 0, even if i put some value on gui in entry it goes to property and i see _selectedAmount as 0.
What could be wrong?
Xaml:
<Entry Placeholder="Amount" Text="{Binding SelectedAmount, Mode=TwoWay}" Keyboard="Numeric" MaxLength="5" />
ViewModel binded property:
private int _selectedAmount;
public int SelectedAmount
{
get => _selectedAmount;
set
{
if (_selectedAmount <= 0)
_pageService.DisplayAlert("Warning", "Value has to be between 1 - 10000", "ok", "cancel");
else
SetValue(ref _selectedAmount, value);
}
}

Your problem is in this line
if (_selectedAmount <= 0)
Whenever you try to enter an number in your entry the setter of SelectedAmount will be called & it will always check for your condition if (_selectedAmount <= 0) & as _selectedAmount hasn't been change throughout the session it will always stays as 0 & return 0, cuz your compiler will never enter the else part & it will never set the input value to _selectedAmount
You have to change your condition as
if (value < 1 || value > 10000)
I guess that's what you was looking for.
Let me know if your issue was something else than this.

Related

Getting error When dt.value length is < 4

I have this code which works fine as long as as dt.Value is different to "int".
This is the line which errors:
(dt.Value.ToLower().Substring(0, 4).Equals("date"))
It works fine if dt.Value is varchar or datetime.
I provided my suggested solution at the end of this post.
// Edit
if (e.CommandName == "Edit")
{
// Get the item
RepeaterItem Item = ((RepeaterItem)((Button)e.CommandSource).NamingContainer);
// Get buttons and repeater
Button savebtn = (Button)(Item.FindControl("btnSave"));
Button editbtn = (Button)(Item.FindControl("btnEdit"));
Repeater rFields = (Repeater)(Item.FindControl("repFields"));
// Enable my fields
foreach (RepeaterItem RI in rFields.Items)
{
// Get data type
HiddenField dt = (HiddenField)(RI.FindControl("hdnDBDataType"));
// Set controls
if (RI.FindControl("chkSetting").Visible) ((CheckBox)RI.FindControl("chkSetting")).Enabled = true;
if (RI.FindControl("ddlSetting").Visible) ((DropDownList)RI.FindControl("ddlSetting")).Enabled = true;
if (RI.FindControl("txtSetting").Visible)
{
((TextBox)RI.FindControl("txtSetting")).Enabled = true;
// Check my data type
if (dt.Value.ToLower().Substring(0, 4).Equals("date")) ((CalendarExtender)RI.FindControl("extDateTime")).Enabled = true;
}
}
}
Is this a good fix ? TIA
if(dt.Value != "int" && dt.Value.ToLower().Substring(0, 4).Equals("date"))
Substring will throw an error if the second parameter is higher than the lenght of the string. What you need to do is check the length before doing the substring or use a method like #Igor suggested in the comments.
Your suggestion to check != "int" is not fullproof if let's say somehow the value is any string less than 4 characters.
(dt.Value.Length > 3 && dt.Value.ToLower().Substring(0, 4).Equals("date"))
I will also put #Igor suggestion here because it is also fullproof:
(dt.Value.StartsWith("date", StringComparison.OrdinalIgnoreCase)

Compare Validator for two dates

I have two labels and two text boxes, a Compare validator and a button.
I need it to compare two dates (rental date , return date ) and when the rental date is less or equal to return date are the same. No validation message.
While when when the rental date is less than the return date, display an input error message.
The compare validator has been set with :
controltocompare : txtrental,
controltovalidate: txtreturndate,
operator :greater than equal,
type:date,
errormessage: return date must be greater or equal than rental date,
I am not sure how to get the btn to display it ?
You need to set the property "CausesValidation" of your button to "true" to trigger validation on its click.
Make sure the CompareValidator has runat="server"
Create a method to display message.
private void AlertBox(string Msg)
{
string s = "alert('" + Msg + "')";
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ckey", s, true);
}
find the code to validate and throw alert message.
if (!String.IsNullOrEmpty(txtrental.Text) && !String.IsNullOrEmpty(txtreturndate.Text))
{
DateTime ssSD = Convert.ToDateTime(txtrental.Text);
DateTime qsED = Convert.ToDateTime(txtreturndate.Text);
int chktxtfd1_sd = ssSD.CompareTo(qsSD);
if ((chktxtfd1_sd == 0 || chktxtfd1_sd == -1) )
{
//do something bcoz condition is true
}
else
{
lvflag = false;
AlertBox("date must be greater or equal than rental date");
}
}
If you find it useful, please mark it as your answer else let me know...

gridview display the text instead of values

my question is:
my table consists of this values: 0, 1, 2 3
but when the gridview loads i want the text to be display instead of just those numbers.
0 = not set, 1 = low, 2 = medium, 3 = high
i could have done this like if/else condition but i just wanted to seek for a optimized sol.
here is my markup gridview:
<asp:TemplateField HeaderText="Priority" SortExpression="Priority" >
<ItemTemplate>
<asp:Label ID="lblPriority" Text='<%# DataBinder.Eval(Container.DataItem,"Priority")%>' runat="server" />
</ItemTemplate>
Assuming you don't have the display values stored in the DB anywhere, this is a way you can implement the rendering part. There may be a more maintainable way to store the lookup values, if anyone could contribute I'd appreciate it.
I wrote this in notepad since I don't have Visual Studio on my machine. Please excuse me if there are any syntax errors.
Markup:
<asp:Label ID="lblPriority" Text='<%# RenderPriority(DataBinder.Eval(Container.DataItem,"Priority")) %>' runat="server" />
Code:
Protected Function RenderPriority(ByVal dbValue As Object) As String
Dim strReturn as String = String.Empty
If Not IsDbNull(dbValue) Then
Dim intValue as Integer
If Integer.TryParse(dbValue, intValue) Then
Select Case intValue
Case 0
strReturn = "not set"
Case 1
strReturn = "low"
Case 2
strReturn = "medium"
Case 3
strReturn = "high"
End Select
Else
strReturn = dbValue.ToString()
End If
End If
Return strReturn
End Function
Edit:
After re-reading your question I get the impression you would prefer to avoid writing a specific function for this purpose in the code-behind page. If that is the case you should probably store the strings you want associated with the key values in the DB and pull them out through your SQL statement. Or, at the very least push the functionality down into a Data Access Layer. Either way ideally the GridView column will be presented with the required string by its datasource.
Why not using enumerations? Here:
Have an enumeration called Priority. Then put Description attribute on each of them, and write the display text inside the constructor of that attribute.
public enum Priority
{
[Description("not set")]
NotSet = 0,
[Description("low")]
Low = 1,
[Description("medium")]
Medium = 2,
[Description("high")]
High = 3
}
Then use Enum.ToObject method to convert the numbers (values) into their associated display value using these functions:
// An extension method for ease of use that converts an integer into enum
public static T ToEnum<T>(this int value)
{
if (typeof(T).BaseType.Name != typeof(Enum).Name)
{
throw new Exception("Input type of generic method ToEnum<T>() is not an Enum");
}
return (T)Enum.ToObject(typeof(T), value);
}
// Another extension method that gets the display text of the Description attribute of a given enum constant
public static string GetDescription(this Enum value)
{
return ((DescriptionAttribute)value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false)[0]).Description;
}
Then in your code, you can write:
databaseValue.ToEnum<Priority>().GetDescription();
You can use the RowDataBound event of the GridView and set the value on specific condition.
Here is the complete code....
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Data.DataRow dr = ((System.Data.DataRowView)e.Row.DataItem).Row;
if (dr["Priority"].ToString() == "0")
{
((Label)e.Row.FindControl("lblPriority")).Text = "not set";
}
else if (dr["Priority"].ToString() == "1")
{
((Label)e.Row.FindControl("lblPriority")).Text = "low";
}
else if (dr["Priority"].ToString() == "2")
{
((Label)e.Row.FindControl("lblPriority")).Text = "medium";
}
else if (dr["Priority"].ToString() == "3")
{
((Label)e.Row.FindControl("lblPriority")).Text = "high";
}
}
}

ASPxGridView - Date format problem

I am getting a problem related to the date format in ASPxGridView.
I have a application in which i am using AspxGridView. I have a column of type combo box which holds the date values.
The column is as
< dxwgv:GridViewDataComboBoxColumn Caption="SERVICE MONTH" Name="ServiceMonthComboBox" Visible=true VisibleIndex="1" FieldName="ServiceMonth">
< EditFormSettings VisibleIndex=1 Visible="false" />< CellStyle HorizontalAlign=Right />
< PropertiesComboBox Style-Font-Names="Verdana" Style-Font-Size="X-Small" TextField="ServiceMonth" ValueField="ServiceMonth">
< Style Font-Names="Verdana" Font-Size="X-Small">< /Style>
< /PropertiesComboBox>< EditFormCaptionStyle ForeColor="Maroon" />
< /dxwgv:GridViewDataComboBoxColumn>
Here, ServiceMonth is of DateTime Type.
At Page_Load event i m using the following code to bind the date data with filter.
GridViewDataComboBoxColumn serviceMonthComboBox = CarHireExchangeGroupSummaryGridView.Columns["ServiceMonthComboBox"] as GridViewDataComboBoxColumn;
serviceMonthComboBox.PropertiesComboBox.ValueType = typeof(DateTime);
serviceMonthComboBox.PropertiesComboBox.Items.Clear();
var serviceMonths = (from item in Presenter.CurrentModel.CarHireExchangeGroupSummaryRecords
select (item.ServiceMonth)).Distinct();
foreach (var serviceMonth in serviceMonths)
{
serviceMonthComboBox.PropertiesComboBox.Items.Add(serviceMonth.ToString("MM/yyyy").Trim(), serviceMonth.ToString("MM/yyyy"));
}
Here, i am binding that combo box with all the distinct ServiceMonth in my records.
Now, i want that, as user filter records using any ServiceMonth, then records should get filter. For that, I have used OnProcessColumnAutoFilter event as follows:
protected void CarHireExchangeGroupSummaryGridView_OnProcessColumnAutoFilter(object sender, ASPxGridViewAutoFilterEventArgs e)
{
if (e.Kind == GridViewAutoFilterEventKind.CreateCriteria)
{
switch (e.Column.FieldName)
{
case "ServiceMonth":
if (!string.IsNullOrEmpty(e.Value))
{
((OperandValue)((BinaryOperator)e.Criteria).RightOperand).Value = Convert.ToDateTime(e.Value.ToString());
}
break;
}
}
}
Now, my problem is that, the value i got is something like this: "Wed Dec 1 00:00:00 CST 2010", now, when i am trying to convert this into DateTime as above code, its giving me the error that "Input string in not in proper DateTime format"
Can you please tell me the reason for this and the way through which i can solve my problem.
Try to set the PropertiesComboBox.ValueType to System.DateTime to force the AutoFilterRow’s ASPxComboBox editor convert Value of its Items to the DateTime values:
<PropertiesComboBox ... ValueType="System.DateTime"></PropertiesComboBox>

Getting values from Dynamic controls in Grid view

I am generating a Gridview with Custom controls (Text boxes) as per the user input during the run time. when i try to access the data in those text boxes, its not happening
I had triggered this operations with the Button and the code is as follows:
for (int rowCount = 0; rowCount <= gvCapacity.Rows.Count; rowCount++)
{
for (int i = 1; i < gvCapacity.Columns.Count; i++)
{
if (i > rowCount)
{
if (!(gvCapacity.Columns[i].HeaderText == "Route" && gvCapacity.Columns[i].HeaderText == "Location" && gvCapacity.Columns[i].HeaderText == "RouteLocationID"))
{
TextBox txtBox = gvCapacity.Rows[rowCount].Cells[i].FindControl("txt" + gvCapacity.Columns[i].HeaderText) as TextBox;
}
}
}
It returns the Null value when i try to access the textbox data.
Can anyone help me out on this.
Regards
Geeta
If you mean the texbox variable "txtbox" is always null it looks like that would be because you're asking that the headertext be two different things in your if conditional:
.. && gvCapacity.Columns[i].HeaderText == "Location" && gvCapacity.Columns[i].HeaderText == "RouteLocationID
which it never will be... one assumes. i.e. FindControl is never evaluated. Maybe one of those && should be an ||?

Resources