MaxLength Property breaks in my custom TextBox - c#

For my WPF apps I have created a couple custom controls based on a TextBox. These include NumericTextBox, WatermarkTextBox, and ReturnTextBox.
Numeric and Watermark inherit from ReturnTextBox, which inherits from TextBox.
When I go to use any of my custom textboxes they work great. The one problem seems to be NumericTextBox and the MaxLength property. The property is now ignored and does not work. There is no code in any of my custom controls overriding or messing with the MaxLength property.
When I use MaxLength on my ReturnTextBox, it works just as you would expect:
<ui:ReturnTextBox MaxLength="35" Width="500" Background="LightYellow" Text="{Binding BrRptCorpName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" TabIndex="2" />
However when I use the property on my NumericTextBox it is ignored and does not work:
<ui:NumericTextBox MaxLength="9" Background="LightYellow" Text="{Binding BrRptAmt, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" TabIndex="1" />
Can anyone help me figure out why MaxLength stops working? Is it because NumericTextBox does not directly inherit from TextBox? Should I be overriding MaxLength property in ReturnTextBox so it can be used by Numeric?
UPDATED WITH CODE
ReturnTextBox class:
public class ReturnTextBox : TextBox
{
static ReturnTextBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ReturnTextBox), new FrameworkPropertyMetadata(typeof(ReturnTextBox)));
}
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Return)
{
e.Handled = true;
MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
base.OnPreviewKeyDown(e);
}
}
NumericTextBox
public class NumericTextBox : ReturnTextBox
{
#region Base Class Overrides
static NumericTextBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NumericTextBox), new FrameworkPropertyMetadata(typeof(NumericTextBox)));
}
public static readonly DependencyProperty TypeProperty = DependencyProperty.Register("Type",
typeof(NumericType), typeof(NumericTextBox), new UIPropertyMetadata (NumericType.Integer));
public static readonly DependencyProperty SelectAllOnGotFocusProperty = DependencyProperty.Register("SelectAllOnGotFocus",
typeof(bool), typeof(NumericTextBox), new PropertyMetadata(false));
[Description("Numeric Type of the TextBox"), Category("Common Properties")]
public NumericType Type
{
get { return (NumericType)GetValue(TypeProperty); }
set { SetValue(TypeProperty, value); }
}
[Description("Select text on focus"), Category("Common Properties")]
public bool SelectAllOnGotFocus
{
get
{
return (bool)GetValue(SelectAllOnGotFocusProperty);
}
set
{
SetValue(SelectAllOnGotFocusProperty, value);
}
}
protected override void OnPreviewTextInput(TextCompositionEventArgs e)
{
Text = ValidateValue(Type, Text);
bool isValid = IsSymbolValid(Type, e.Text);
e.Handled = !isValid;
if (isValid)
{
int caret = CaretIndex;
string text = Text;
bool textInserted = false;
int selectionLength = 0;
if (SelectionLength > 0)
{
text = text.Substring(0, SelectionStart) + text.Substring(SelectionStart + SelectionLength);
caret = SelectionStart;
}
if (e.Text == NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
{
while (true)
{
int ind = text.IndexOf(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
if (ind == -1)
break;
text = text.Substring(0, ind) + text.Substring(ind + 1);
if (caret > ind)
caret--;
}
if (caret == 0)
{
text = "0" + text;
caret++;
}
else
{
if (caret == 1 && string.Empty + text[0] == NumberFormatInfo.CurrentInfo.NegativeSign)
{
text = NumberFormatInfo.CurrentInfo.NegativeSign + "0" + text.Substring(1);
caret++;
}
}
if (caret == text.Length)
{
selectionLength = 1;
textInserted = true;
text = text + NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + "0";
caret++;
}
}
else if (e.Text == NumberFormatInfo.CurrentInfo.NegativeSign)
{
textInserted = true;
if (Text.Contains(NumberFormatInfo.CurrentInfo.NegativeSign))
{
text = text.Replace(NumberFormatInfo.CurrentInfo.NegativeSign, string.Empty);
if (caret != 0)
caret--;
}
else
{
text = NumberFormatInfo.CurrentInfo.NegativeSign + Text;
caret++;
}
}
if (!textInserted)
{
text = text.Substring(0, caret) + e.Text +
((caret < Text.Length) ? text.Substring(caret) : string.Empty);
caret++;
}
try
{
double val = Convert.ToDouble(text);
double newVal = val;//ValidateLimits(GetMinimumValue(_this), GetMaximumValue(_this), val);
if (val != newVal)
{
text = newVal.ToString();
}
else if (val == 0)
{
if (!text.Contains(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator))
text = "0";
}
}
catch
{
text = "0";
}
while (text.Length > 1 && text[0] == '0' && string.Empty + text[1] != NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
{
text = text.Substring(1);
if (caret > 0)
caret--;
}
while (text.Length > 2 && string.Empty + text[0] == NumberFormatInfo.CurrentInfo.NegativeSign && text[1] == '0' && string.Empty + text[2] != NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
{
text = NumberFormatInfo.CurrentInfo.NegativeSign + text.Substring(2);
if (caret > 1)
caret--;
}
if (caret > text.Length)
caret = text.Length;
Text = text;
CaretIndex = caret;
SelectionStart = caret;
SelectionLength = selectionLength;
e.Handled = true;
}
base.OnPreviewTextInput(e);
}
private static string ValidateValue(NumericType type, string value)
{
if (string.IsNullOrEmpty(value))
return string.Empty;
value = value.Trim();
switch (type)
{
case NumericType.Integer:
try
{
Convert.ToInt64(value);
return value;
}
catch
{
}
return string.Empty;
case NumericType.Decimal:
try
{
Convert.ToDouble(value);
return value;
}
catch
{
}
return string.Empty;
}
return value;
}
private static bool IsSymbolValid(NumericType type, string str)
{
switch (type)
{
case NumericType.Decimal:
if (str == NumberFormatInfo.CurrentInfo.NegativeSign ||
str == NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
return true;
break;
case NumericType.Integer:
if (str == NumberFormatInfo.CurrentInfo.NegativeSign)
return true;
break;
case NumericType.Any:
return true;
}
if (type.Equals(NumericType.Integer) || type.Equals(NumericType.Decimal))
{
foreach (char ch in str)
{
if (!Char.IsDigit(ch))
return false;
}
return true;
}
return false;
}
protected override void OnGotFocus(RoutedEventArgs e)
{
base.OnGotFocus(e);
if (SelectAllOnGotFocus)
SelectAll();
}
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (!IsKeyboardFocused && SelectAllOnGotFocus)
{
e.Handled = true;
Focus();
}
base.OnPreviewMouseLeftButtonDown(e);
}
As you can see I never override or make any changes to the MaxLength property in either of these two controls. However the MaxLength works with the ReturnTextBox and does not work with the NumericTextBox.
Thank you for your help!

e.Handled = !isValid and if(isValid) { e.Handled = true } are your problem. When you use the PreviewSomeEvent the they are tunneling. That means they go from the root and down to the source that caused the event. Setting the Handled property on the event means that other handlers in the events route won't be raised. MaxLength is something defined on the TextBox or at least on something more "primite" than your NumericTextBox.
What happens is that if the users input fail your validation, the event won't be raised "deeper down the tunnel" to check the length: e.Handled = !isValid. And if it passes your validation it wont be raised either because e.Handled = true.
Perhaps a useful analogy can be overriding a method and calling base or not.
For more on events check here

Related

Change row color in datagridview

I know it's already been written about.
Everything looks very good. But when I move to the right to see the rest of the columns, the rows in DataDridView start blinking very much. I can't solve this.
private void registersDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridViewRow rowDataGridView = null;
string dataPropertyName;
dataPropertyName = this.registersDataGridView.Columns[e.ColumnIndex].DataPropertyName;
int isApprovedColumnIndex = this.registersDataGridView.Columns[isApprovedColumnName].Index;
int isCancelledColumnIndex = this.registersDataGridView.Columns[isCancelledColumnName].Index;
bool theColorHasBeenSet = false;
if (e.RowIndex >= 0 && e.RowIndex != btregisterDgvRowIndex)
{
rowDataGridView = this.registersDataGridView.Rows[e.RowIndex];
if (this.registersDataGridView.Columns[isCancelledColumnIndex].DataPropertyName == "IsCancelled")
{
if (rowDataGridView.Cells[isCancelledColumnIndex].Value != null && rowDataGridView.Cells[isCancelledColumnIndex].Value.ToString() == "Tak")
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.PaleVioletRed)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.PaleVioletRed;
}
theColorHasBeenSet = true;
}
else
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.Ivory)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.Ivory;
}
}
btregisterDgvRowIndex = e.RowIndex;
}
if (this.registersDataGridView.Columns[isApprovedColumnIndex].DataPropertyName == "IsApproved")
{
if (!theColorHasBeenSet)
{
if (rowDataGridView.Cells[isApprovedColumnName].Value != null && rowDataGridView.Cells[isApprovedColumnName].Value.ToString() == "-")
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.LightGray)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.LightGray;
}
theColorHasBeenSet = true;
}
else if (rowDataGridView.Cells[isApprovedColumnName].Value != null && rowDataGridView.Cells[isApprovedColumnName].Value.ToString() == "Nie")
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.PaleVioletRed)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.PaleVioletRed;
}
theColorHasBeenSet = true;
}
else
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.Ivory)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.Ivory;
}
}
btregisterDgvRowIndex = e.RowIndex;
}
}
}
}
else
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.Ivory)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.Ivory;
}
}
You're not setting the theColorHasBeenSet here which might cause it to change between Ivory and the next color on your list.
Your code seems to verbose to me, try the following
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex < 0)
return;
var rowDataGridView = this.registersDataGridView.Rows[e.RowIndex];
Color GetBackgroundColor()
{
var isApprovedColumnIndex = this.registersDataGridView.Columns[isApprovedColumnName].Index;
var isCancelledColumnIndex = this.registersDataGridView.Columns[isCancelledColumnName].Index;
if (this.registersDataGridView.Columns[isCancelledColumnIndex].DataPropertyName == "IsCancelled")
{
var strValue = Convert.ToString(rowDataGridView.Cells[isCancelledColumnIndex].Value);
if (strValue == "Tak")
return Color.PaleVioletRed;
}
if (this.registersDataGridView.Columns[isApprovedColumnIndex].DataPropertyName == "IsApproved")
{
var strValue = Convert.ToString(rowDataGridView.Cells[isApprovedColumnIndex].Value);
if (strValue == "-")
return Color.LightGray;
if (strValue == "Nie")
return Color.PaleVioletRed;
}
return Color.Ivory;
}
rowDataGridView.DefaultCellStyle.BackColor = GetBackgroundColor();
}

How to make a xaml textbox in silverlight accept only numbers with maximum one decimal point precision

How to make a xaml textbox in silverlight accept only numbers with maximum one decimal point precison. I have tried the answers in this question How to make a textBox accept only Numbers and just one decimal point in Windows 8. But it did not work. How can I do this ?
You can write a function like this,
txtDiscount.KeyDown += new KeyEventHandler(EnsureNumbers);
//Method to allow only numbers,
void EnsureNumbers(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
return;
}
bool result = EnsureDecimalPlaces();
if (result == false)
{
var thisKeyStr = "";
if (e.PlatformKeyCode == 190 || e.PlatformKeyCode == 110)
{
thisKeyStr = ".";
}
else
{
thisKeyStr = e.Key.ToString().Replace("D", "").Replace("NumPad", "");
}
var s = (sender as TextBox).Text + thisKeyStr;
var rStr = "^[0-9]+[.]?[0-9]*$";
var r = new Regex(rStr, RegexOptions.IgnoreCase);
e.Handled = !r.IsMatch(s);
}
else
{
e.Handled = true;
}
}
Method to ensure only 1 decimal,
bool EnsureDecimalPlaces()
{
string inText = txtDiscount.Text;
int decPointIndex = inText.IndexOf('.');
if (decPointIndex < 1 || decPointIndex == 1)
{
return false;
}
else
return true;
}

How to get selected value or index of a dropdownlist upon entering a page?

I have a product ordering page with various product option dropdownlists which are inside a repeater. The "Add To Cart" button is "inactive" until all the options have a selection. Technically, the "Add To Cart" button has two images: a grey one which is used when the user has not selected choices for all options available to a product and an orange one which is used when the user has made a selection from each dropdownlist field.These images are set by the ShowAddToBasket and HideAddToBasket functions.
The dropdownlist fields are connected in that a selection from the first field will determine a selection for the second and sometimes third field. If the second field is NOT pre-set by the first field, then the second field will determine the value for the third field. The first dropdownlist field is never disabled, but the other two can be based on what options have been selected.
There are a few products that have all 3 of their dropdownlists pre-set to certain choices upon entering their page. This means they are all disabled and cannot be changed by the user. Regardless of whether the user enters in a quantity or not, the "Add To Cart" button NEVER activates. I cannot for the life of me figure out how to change it so that, in these rare circumstances, the "Add to Cart" button is automatically set to active once a quantity has been entered. The dropdownlists still have options selected in these pages--it's just that they are fixed and cannot be changed by the user.
Is there anyway I can get the selected value or selected index of these dropdownlist fields upon entering a product page? I want to be able to check to see if they are truly "empty" or if they do have selections made so I can set the "Add to Cart" button accordingly.
Any help would be great because I'm really stuck on this one! :(
Here is the code behind (I removed a lot of the unimportant functions):
protected void Page_Init(object sender, System.EventArgs e)
{
string MyPath = HttpContext.Current.Request.Url.AbsolutePath;
MyPath = MyPath.ToLower();
_Basket = AbleContext.Current.User.Basket;
RedirQryStr = "";
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
if (Request.QueryString["LineID"] != null)
{
int LineID = Convert.ToInt32(Request.QueryString["LineID"].ToString());
int itemIndex = _Basket.Items.IndexOf(LineID);
BasketItem item = _Basket.Items[itemIndex];
OldWeight.Text = item.Weight.ToString();
OldQty.Text = item.Quantity.ToString();
OldPrice.Text = item.Price.ToString();
}
int UnitMeasure = 0;
SetBaidCustoms(ref UnitMeasure);
GetPrefinishNote();
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
_Product = ProductDataSource.Load(_ProductId);
if (_Product != null)
{
//GetPercentage();
int _PieceCount = 0;
double _SurchargePercent = 0;
CheckoutHelper.GetItemSurcargePercent(_Product, ref _PieceCount, ref _SurchargePercent);
SurchargePieceCount.Text = _PieceCount.ToString();
SurchargePercent.Text = _SurchargePercent.ToString();
//add weight
BaseWeight.Value = _Product.Weight.ToString();
//DISABLE PURCHASE CONTROLS BY DEFAULT
AddToBasketButton.Visible = false;
rowQuantity.Visible = false;
//HANDLE SKU ROW
trSku.Visible = (ShowSku && (_Product.Sku != string.Empty));
if (trSku.Visible)
{
Sku.Text = _Product.Sku;
}
//HANDLE PART/MODEL NUMBER ROW
trPartNumber.Visible = (ShowPartNumber && (_Product.ModelNumber != string.Empty));
if (trPartNumber.Visible)
{
PartNumber.Text = _Product.ModelNumber;
}
//HANDLE REGPRICE ROW
if (ShowMSRP)
{
decimal msrpWithVAT = TaxHelper.GetShopPrice(_Product.MSRP, _Product.TaxCode != null ? _Product.TaxCode.Id : 0);
if (msrpWithVAT > 0)
{
trRegPrice.Visible = true;
RegPrice.Text = msrpWithVAT.LSCurrencyFormat("ulc");
}
else trRegPrice.Visible = false;
}
else trRegPrice.Visible = false;
// HANDLE PRICES VISIBILITY
if (ShowPrice)
{
if (!_Product.UseVariablePrice)
{
trBasePrice.Visible = true;
BasePrice.Text = _Product.Price.ToString("F2") + BairdLookUp.UnitOfMeasure(UnitMeasure);
trOurPrice.Visible = true;
trVariablePrice.Visible = false;
}
else
{
trOurPrice.Visible = false;
trVariablePrice.Visible = true;
VariablePrice.Text = _Product.Price.ToString("F2");
string varPriceText = string.Empty;
Currency userCurrency = AbleContext.Current.User.UserCurrency;
decimal userLocalMinimum = userCurrency.ConvertFromBase(_Product.MinimumPrice.HasValue ? _Product.MinimumPrice.Value : 0);
decimal userLocalMaximum = userCurrency.ConvertFromBase(_Product.MaximumPrice.HasValue ? _Product.MaximumPrice.Value : 0);
if (userLocalMinimum > 0)
{
if (userLocalMaximum > 0)
{
varPriceText = string.Format("(between {0} and {1})", userLocalMinimum.LSCurrencyFormat("ulcf"), userLocalMaximum.LSCurrencyFormat("ulcf"));
}
else
{
varPriceText = string.Format("(at least {0})", userLocalMinimum.LSCurrencyFormat("ulcf"));
}
}
else if (userLocalMaximum > 0)
{
varPriceText = string.Format("({0} maximum)", userLocalMaximum.LSCurrencyFormat("ulcf"));
}
phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
}
}
//UPDATE QUANTITY LIMITS
if ((_Product.MinQuantity > 0) && (_Product.MaxQuantity > 0))
{
string format = " (min {0}, max {1})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity, _Product.MaxQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
QuantityX.MaxValue = _Product.MaxQuantity;
}
else if (_Product.MinQuantity > 0)
{
string format = " (min {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
}
else if (_Product.MaxQuantity > 0)
{
string format = " (max {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MaxQuantity)));
QuantityX.MaxValue = _Product.MaxQuantity;
}
if (QuantityX.MinValue > 0) QuantityX.Text = QuantityX.MinValue.ToString();
AddToWishlistButton.Visible = AbleContext.Current.StoreMode == StoreMode.Standard;
}
else
{
this.Controls.Clear();
}
if (!Page.IsPostBack)
{
if (Request.QueryString["Action"] != null)
{
if (Request.QueryString["Action"].ToString().ToLower() == "edit")
{
SetEdit();
}
}
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (_Product != null)
{
if (ViewState["OptionDropDownIds"] != null)
{
_OptionDropDownIds = (Hashtable)ViewState["OptionDropDownIds"];
}
else
{
_OptionDropDownIds = new Hashtable();
}
if (ViewState["OptionPickerIds"] != null)
{
_OptionPickerIds = (Hashtable)ViewState["OptionPickerIds"];
}
else
{
_OptionPickerIds = new Hashtable();
}
_SelectedOptionChoices = GetSelectedOptionChoices();
OptionsList.DataSource = GetProductOptions();
OptionsList.DataBind();
//set all to the first value
foreach (RepeaterItem rptItem in OptionsList.Items)
{
DropDownList OptionChoices = (DropDownList)rptItem.FindControl("OptionChoices");
OptionChoices.SelectedIndex = 1;
}
TemplatesList.DataSource = GetProductTemplateFields();
TemplatesList.DataBind();
KitsList.DataSource = GetProductKitComponents();
KitsList.DataBind();
}
if (!Page.IsPostBack)
{
if (_Product.MSRP != 0)
{
salePrice.Visible = true;
RetailPrice.Text = _Product.MSRP.ToString("$0.00");
}
DataSet ds = new DataSet();
DataTable ResultTable = ds.Tables.Add("CatTable");
ResultTable.Columns.Add("OptionID", Type.GetType("System.String"));
ResultTable.Columns.Add("OptionName", Type.GetType("System.String"));
ResultTable.Columns.Add("LinkHeader", Type.GetType("System.String"));
foreach (ProductOption PhOpt in _Product.ProductOptions)
{
string MasterList = GetProductMaster(_ProductId, PhOpt.OptionId);
string PerFootVal = "";
string LinkHeader = "";
string DefaultOption = "no";
string PrefinishMin = "0";
bool VisPlaceholder = true;
ProductDisplayHelper.TestForVariantDependency(ref SlaveHide, _ProductId, PhOpt, ref PrefinishMin, ref PerFootVal, ref LinkHeader, ref VisPlaceholder, ref HasDefault, ref DefaultOption);
if (PrefinishMin == "")
PrefinishMin = "0";
DataRow dr = ResultTable.NewRow();
dr["OptionID"] = PhOpt.OptionId + ":" + MasterList + ":" + PerFootVal + ":" + DefaultOption + ":" + PrefinishMin;
Option _Option = OptionDataSource.Load(PhOpt.OptionId);
dr["OptionName"] = _Option.Name;
dr["LinkHeader"] = LinkHeader;
ResultTable.Rows.Add(dr);
}
//Bind the data to the Repeater
ItemOptions.DataSource = ds;
ItemOptions.DataMember = "CatTable";
ItemOptions.DataBind();
//determine if buttons show
if (ItemOptions.Items.Count == 0)
{
ShowAddToBasket(1);
resetBtn.Visible = true;
}
else
{
HideAddToBasket(3);
}
if (Request.QueryString["Action"] != null)
{
ShowAddToBasket(1);
SetDllAssociation(false);
}
ShowHideDrops();
}
}
private void HideAddToBasket(int Location)
{
AddToBasketButton.Visible = false;
AddToWishlistButton.Visible = false;
resetBtn.Visible = false;
if (Request.QueryString["Action"] == null)
{
SelectAll.Visible = true;
WishGray.Visible = true;
if (Request.QueryString["OrderItemID"] == null)
BasketGray.Visible = true;
else
UpdateButton.Visible = false;
}
else
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
}
}
private void ShowAddToBasket(int place)
{
resetBtn.Visible = true;
if (Request.QueryString["Action"] != null)
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
else
{
UpdateButton.Visible = false;
SelectAll.Visible = false;
WishGray.Visible = false;
BasketGray.Visible = false;
if (Request.QueryString["OrderItemID"] == null)
{
AddToBasketButton.Visible = true;
resetBtn.Visible = true;
AddToWishlistButton.Visible = true;
}
else
{
UpdateButton.Visible = true;
AddToBasketButton.Visible = false;
}
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
resetBtn.Visible = true;
}
}
protected void OptionChoices_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
if (ddl != null)
{
//bb5.Text = "ddl !=null<br />"; works
List<OptionChoiceItem> ds = (List<OptionChoiceItem>)ddl.DataSource;
if (ds != null && ds.Count > 0)
{
int optionId = ds[0].OptionId;
Option opt = OptionDataSource.Load(optionId);
ShowAddToBasket(4);
OptionChoiceItem oci = ds.FirstOrDefault<OptionChoiceItem>(c => c.Selected);
if (oci != null)
{
ListItem item = ddl.Items.FindByValue(oci.ChoiceId.ToString());
if (item != null)
{
ddl.ClearSelection();
item.Selected = true;
}
}
if (opt != null && !opt.ShowThumbnails)
{
if (!_OptionDropDownIds.Contains(optionId))
{
// bb5.Text = "!_OptionDropDownIds.Contains(optionId)<br />"; works
_OptionDropDownIds.Add(optionId, ddl.UniqueID);
}
if (_SelectedOptionChoices.ContainsKey(optionId))
{
ListItem selectedItem = ddl.Items.FindByValue(_SelectedOptionChoices[optionId].ToString());
if (selectedItem != null)
{
ddl.ClearSelection();
selectedItem.Selected = true;
//bb5.Text = "true: " + selectedItem.Selected.ToString()+"<br />"; doesn't work
}
}
StringBuilder imageScript = new StringBuilder();
imageScript.Append("<script type=\"text/javascript\">\n");
imageScript.Append(" var " + ddl.ClientID + "_Images = {};\n");
foreach (OptionChoice choice in opt.Choices)
{
if (!string.IsNullOrEmpty(choice.ImageUrl))
{
imageScript.Append(" " + ddl.ClientID + "_Images[" + choice.Id.ToString() + "] = '" + this.Page.ResolveUrl(choice.ImageUrl) + "';\n");
}
}
imageScript.Append("</script>\n");
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager != null)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), ddl.ClientID, imageScript.ToString(), false);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), ddl.ClientID, imageScript.ToString());
}
}
}
ddl.Attributes.Add("onChange", "OptionSelectionChanged('" + ddl.ClientID + "');");
}
}
protected Dictionary<int, int> GetSelectedOptionChoices()
{
HttpRequest request = HttpContext.Current.Request;
Dictionary<int, int> selectedChoices = new Dictionary<int, int>();
if (Page.IsPostBack)
{
foreach (int key in _OptionDropDownIds.Keys)
{
string value = (string)_OptionDropDownIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} DropDownId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
foreach (int key in _OptionPickerIds.Keys)
{
string value = (string)_OptionPickerIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} PickerId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
}
else
{
string optionList = Request.QueryString["Options"];
ShowAddToBasket(2);
if (!string.IsNullOrEmpty(optionList))
{
string[] optionChoices = optionList.Split(',');
if (optionChoices != null)
{
foreach (string optionChoice in optionChoices)
{
OptionChoice choice = OptionChoiceDataSource.Load(AlwaysConvert.ToInt(optionChoice));
if (choice != null)
{
_SelectedOptionChoices.Add(choice.OptionId, choice.Id);
}
}
return _SelectedOptionChoices;
}
}
}
return selectedChoices;
}
protected void SetDDLs(object sender, EventArgs e)
{
bool isRandom = false;
if (LengthDDL.Text != "")
isRandom = true;
SetDllAssociation(isRandom);
}
Try accessing the values in the Page_Load event. I don't believe the values are bound yet in Page_Init

To check if var is String type

I have a problem in code in C#:
I don't know how to implement logic - iterating through Hashtable
having values of different data types, the schema I want is below:
if the value in variable is String type
{
do action1;
}
else
{
do action2;
}
There is a hashtable containing data of Types - String and Int (combined):
public string SQLCondGenerator {
get
{
Hashtable conditions = new Hashtable();
//data having String data type
conditions.Add("miap", ViewState["miap_txt"]);
conditions.Add("pocode", ViewState["po_txt "]);
conditions.Add("materialdescription", ViewState["mat_desc_txt"]);
conditions.Add("suppliername", ViewState["supplier_txt"]);
conditions.Add("manufacturername", ViewState["manufacturer_txt"]);
//data having Int32 data type
conditions.Add("spareparts", ViewState["sp_id"]);
conditions.Add("firstfills", ViewState["ff_id"]);
conditions.Add("specialtools", ViewState["st_id"]);
conditions.Add("ps_deleted", ViewState["ps_del_id"]);
conditions.Add("po_manuallyinserted", ViewState["man_ins_id"]);
String SQLCondString = "";
String SQLCondStringConverted = "";
string s = string.Empty;
foreach (string name in conditions.Keys)
{
if (conditions[name] != null)
{
SQLCondString += name+ "=" +conditions[name]+ " and ";
Response.Write(conditions[name].GetType());
bool valtype = conditions[name].GetType().IsValueType;
if (valtype == string)
{
SQLCondString.Substring(0, SQLCondString.Length - 4);
SQLCondString += name + " and like '%" + conditions[name] + "%' and ";
}
}
}
//Response.Write("********************");
SQLCondStringConverted = SQLCondString.Substring(0, SQLCondString.Length - 4);
return SQLCondStringConverted;
}
}
May be I am wrong in coding, please advise!
Thanks!
if(conditions[name] is string)
{
}
else
{
}
Hmm, I'm not sure why you are calling IsValueType, but this should be sufficient:
if (conditions[name] is string)
{
///
}
Approach - 1
Int32 Val = 0;
if (Int32.TryParse("Your Value", out Val))
{
//Your Logic for int
}
else
{
//Your Logic for String
}
Approach - 2 (using Late Binding)
Int32 Val = 0;
dynamic conditions = new Hashtable();
conditions.Add("miap", ViewState["miap_txt"]);
conditions.Add("pocode", ViewState["po_txt "]);
foreach (string name in conditions.Keys)
{
if (Int32.TryParse(conditions[name].ToString(), out Val))
{
//Your Logic for int
}
else
{
//Your Logic for String
}
}
I had the same issue but I was using textBoxes and needed to validate if the input is alphabets,-, or .
I generated a keypress event on my textBox and inserted the following method to check each keypress and give a prompt if its not a valid character:
public static class Validator
{
public static bool IsNameString(TextBox tb, string name, KeyPressEventArgs e)
{
bool valid = true;
/* e.KeyChar contains the character that was pressed
e.Handled is a boolean that indicates that handling is done
if a bad character is entered, set e.Handled to true
*/
if (!char.IsLetter(e.KeyChar) && e.KeyChar != ' ' && e.KeyChar != '-' &&
e.KeyChar != '.' && e.KeyChar != (char)Keys.Back)
{
e.Handled = true;
valid = false;
MessageBox.Show(name+ " can only accept letters, space, - and .");
tb.Focus();
}
return valid;
}
}
usage:
private void txtCustomerName_KeyPress(object sender, KeyPressEventArgs e)
{
Validator.IsNameString(txtCustomerName, "Customer Name", e);
}

Numeric Data Entry in WPF

How are you handling the entry of numeric values in WPF applications?
Without a NumericUpDown control, I've been using a TextBox and handling its PreviewKeyDown event with the code below, but it's pretty ugly.
Has anyone found a more graceful way to get numeric data from the user without relying on a third-party control?
private void NumericEditPreviewKeyDown(object sender, KeyEventArgs e)
{
bool isNumPadNumeric = (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal;
bool isNumeric = (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod;
if ((isNumeric || isNumPadNumeric) && Keyboard.Modifiers != ModifierKeys.None)
{
e.Handled = true;
return;
}
bool isControl = ((Keyboard.Modifiers != ModifierKeys.None && Keyboard.Modifiers != ModifierKeys.Shift)
|| e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Insert
|| e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up
|| e.Key == Key.Tab
|| e.Key == Key.PageDown || e.Key == Key.PageUp
|| e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Escape
|| e.Key == Key.Home || e.Key == Key.End);
e.Handled = !isControl && !isNumeric && !isNumPadNumeric;
}
How about:
protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
{
e.Handled = !AreAllValidNumericChars(e.Text);
base.OnPreviewTextInput(e);
}
private bool AreAllValidNumericChars(string str)
{
foreach(char c in str)
{
if(!Char.IsNumber(c)) return false;
}
return true;
}
This is how I do it. It uses a regular expression to check if the text that will be in the box is numeric or not.
Regex NumEx = new Regex(#"^-?\d*\.?\d*$");
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (sender is TextBox)
{
string text = (sender as TextBox).Text + e.Text;
e.Handled = !NumEx.IsMatch(text);
}
else
throw new NotImplementedException("TextBox_PreviewTextInput Can only Handle TextBoxes");
}
There is now a much better way to do this in WPF and Silverlight. If your control is bound to a property, all you have to do is change your binding statement a bit. Use the following for your binding:
<TextBox Text="{Binding Number, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/>
Note that you can use this on custom properties too, all you have to do is throw an exception if the value in the box is invalid and the control will get highlighted with a red border. If you click on the upper right of the red border then the exception message will pop up.
I've been using an attached property to allow the user to use the up and down keys to change the values in the text box. To use it, you just use
<TextBox local:TextBoxNumbers.SingleDelta="1">100</TextBox>
This doesn't actually address the validation issues that are referred to in this question, but it addresses what I do about not having a numeric up/down control. Using it for a little bit, I think I might actually like it better than the old numeric up/down control.
The code isn't perfect, but it handles the cases I needed it to handle:
Up arrow, Down arrow
Shift + Up arrow, Shift + Down arrow
Page Up, Page Down
Binding Converter on the text property
Code behind
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
namespace Helpers
{
public class TextBoxNumbers
{
public static Decimal GetSingleDelta(DependencyObject obj)
{
return (Decimal)obj.GetValue(SingleDeltaProperty);
}
public static void SetSingleDelta(DependencyObject obj, Decimal value)
{
obj.SetValue(SingleDeltaProperty, value);
}
// Using a DependencyProperty as the backing store for SingleValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SingleDeltaProperty =
DependencyProperty.RegisterAttached("SingleDelta", typeof(Decimal), typeof(TextBoxNumbers), new UIPropertyMetadata(0.0m, new PropertyChangedCallback(f)));
public static void f(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
TextBox t = o as TextBox;
if (t == null)
return;
t.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(t_PreviewKeyDown);
}
private static Decimal GetSingleValue(DependencyObject obj)
{
return GetSingleDelta(obj);
}
private static Decimal GetDoubleValue(DependencyObject obj)
{
return GetSingleValue(obj) * 10;
}
private static Decimal GetTripleValue(DependencyObject obj)
{
return GetSingleValue(obj) * 100;
}
static void t_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
TextBox t = sender as TextBox;
Decimal i;
if (t == null)
return;
if (!Decimal.TryParse(t.Text, out i))
return;
switch (e.Key)
{
case System.Windows.Input.Key.Up:
if (Keyboard.Modifiers == ModifierKeys.Shift)
i += GetDoubleValue(t);
else
i += GetSingleValue(t);
break;
case System.Windows.Input.Key.Down:
if (Keyboard.Modifiers == ModifierKeys.Shift)
i -= GetDoubleValue(t);
else
i -= GetSingleValue(t);
break;
case System.Windows.Input.Key.PageUp:
i += GetTripleValue(t);
break;
case System.Windows.Input.Key.PageDown:
i -= GetTripleValue(t);
break;
default:
return;
}
if (BindingOperations.IsDataBound(t, TextBox.TextProperty))
{
try
{
Binding binding = BindingOperations.GetBinding(t, TextBox.TextProperty);
t.Text = (string)binding.Converter.Convert(i, null, binding.ConverterParameter, binding.ConverterCulture);
}
catch
{
t.Text = i.ToString();
}
}
else
t.Text = i.ToString();
}
}
}
I decided to simplify the reply marked as the answer on here to basically 2 lines using a LINQ expression.
e.Handled = !e.Text.All(Char.IsNumber);
base.OnPreviewTextInput(e);
Why don't you just try using the KeyDown event rather than the PreviewKeyDown Event. You can stop the invalid characters there, but all the control characters are accepted. This seems to work for me:
private void NumericKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
bool isNumPadNumeric = (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9);
bool isNumeric =((e.Key >= Key.D0 && e.Key <= Key.D9) && (e.KeyboardDevice.Modifiers == ModifierKeys.None));
bool isDecimal = ((e.Key == Key.OemPeriod || e.Key == Key.Decimal) && (((TextBox)sender).Text.IndexOf('.') < 0));
e.Handled = !(isNumPadNumeric || isNumeric || isDecimal);
}
I use a custom ValidationRule to check if text is numeric.
public class DoubleValidation : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value is string)
{
double number;
if (!Double.TryParse((value as string), out number))
return new ValidationResult(false, "Please enter a valid number");
}
return ValidationResult.ValidResult;
}
Then when I bind a TextBox to a numeric property, I add the new custom class to the Binding.ValidationRules collection. In the example below the validation rule is checked everytime the TextBox.Text changes.
<TextBox>
<TextBox.Text>
<Binding Path="MyNumericProperty" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:DoubleValidation/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
public class NumericTextBox : TextBox
{
public NumericTextBox()
: base()
{
DataObject.AddPastingHandler(this, new DataObjectPastingEventHandler(CheckPasteFormat));
}
private Boolean CheckFormat(string text)
{
short val;
return Int16.TryParse(text, out val);
}
private void CheckPasteFormat(object sender, DataObjectPastingEventArgs e)
{
var isText = e.SourceDataObject.GetDataPresent(System.Windows.DataFormats.Text, true);
if (isText)
{
var text = e.SourceDataObject.GetData(DataFormats.Text) as string;
if (CheckFormat(text))
{
return;
}
}
e.CancelCommand();
}
protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
{
if (!CheckFormat(e.Text))
{
e.Handled = true;
}
else
{
base.OnPreviewTextInput(e);
}
}
}
Additionally you may customize the parsing behavior by providing appropriate dependency properties.
Combining the ideas from a few of these answers, I have created a NumericTextBox that
Handles decimals
Does some basic validation to ensure any entered '-' or '.' is valid
Handles pasted values
Please feel free to update if you can think of any other logic that should be included.
public class NumericTextBox : TextBox
{
public NumericTextBox()
{
DataObject.AddPastingHandler(this, OnPaste);
}
private void OnPaste(object sender, DataObjectPastingEventArgs dataObjectPastingEventArgs)
{
var isText = dataObjectPastingEventArgs.SourceDataObject.GetDataPresent(System.Windows.DataFormats.Text, true);
if (isText)
{
var text = dataObjectPastingEventArgs.SourceDataObject.GetData(DataFormats.Text) as string;
if (IsTextValid(text))
{
return;
}
}
dataObjectPastingEventArgs.CancelCommand();
}
private bool IsTextValid(string enteredText)
{
if (!enteredText.All(c => Char.IsNumber(c) || c == '.' || c == '-'))
{
return false;
}
//We only validation against unselected text since the selected text will be replaced by the entered text
var unselectedText = this.Text.Remove(SelectionStart, SelectionLength);
if (enteredText == "." && unselectedText.Contains("."))
{
return false;
}
if (enteredText == "-" && unselectedText.Length > 0)
{
return false;
}
return true;
}
protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
{
e.Handled = !IsTextValid(e.Text);
base.OnPreviewTextInput(e);
}
}
You can also try using data validation if users commit data before you use it. Doing that I found was fairly simple and cleaner than fiddling about with keys.
Otherwise, you could always disable Paste too!
My Version of Arcturus answer, can change the convert method used to work with int / uint / decimal / byte (for colours) or any other numeric format you care to use, also works with copy / paste
protected override void OnPreviewTextInput( System.Windows.Input.TextCompositionEventArgs e )
{
try
{
if ( String.IsNullOrEmpty( SelectedText ) )
{
Convert.ToDecimal( this.Text.Insert( this.CaretIndex, e.Text ) );
}
else
{
Convert.ToDecimal( this.Text.Remove( this.SelectionStart, this.SelectionLength ).Insert( this.SelectionStart, e.Text ) );
}
}
catch
{
// mark as handled if cannot convert string to decimal
e.Handled = true;
}
base.OnPreviewTextInput( e );
}
N.B. Untested code.
Add this to the main solution to make sure the the binding is updated to zero when the textbox is cleared.
protected override void OnPreviewKeyUp(System.Windows.Input.KeyEventArgs e)
{
base.OnPreviewKeyUp(e);
if (BindingOperations.IsDataBound(this, TextBox.TextProperty))
{
if (this.Text.Length == 0)
{
this.SetValue(TextBox.TextProperty, "0");
this.SelectAll();
}
}
}
Call me crazy, but why not put plus and minus buttons at either side of the TextBox control and simply prevent the TextBox from receiving cursor focus, thereby creating your own cheap NumericUpDown control?
private void txtNumericValue_PreviewKeyDown(object sender, KeyEventArgs e)
{
KeyConverter converter = new KeyConverter();
string key = converter.ConvertToString(e.Key);
if (key != null && key.Length == 1)
{
e.Handled = Char.IsDigit(key[0]) == false;
}
}
This is the easiest technique I've found to accomplish this. The down side is that the context menu of the TextBox still allows non-numerics via Paste. To resolve this quickly I simply added the attribute/property: ContextMenu="{x:Null}" to the TextBox thereby disabling it. Not ideal but for my scenario it will suffice.
Obviously you could add a few more keys/chars in the test to include additional acceptable values (e.g. '.', '$' etc...)
Private Sub Value1TextBox_PreviewTextInput(ByVal sender As Object, ByVal e As TextCompositionEventArgs) Handles Value1TextBox.PreviewTextInput
Try
If Not IsNumeric(e.Text) Then
e.Handled = True
End If
Catch ex As Exception
End Try
End Sub
Worked for me.
Can you not just use something like the following?
int numericValue = 0;
if (false == int.TryParse(yourInput, out numericValue))
{
// handle non-numeric input
}
void PreviewTextInputHandler(object sender, TextCompositionEventArgs e)
{
string sVal = e.Text;
int val = 0;
if (sVal != null && sVal.Length > 0)
{
if (int.TryParse(sVal, out val))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
}
Can also use a converter like:
public class IntegerFormatConverter : IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int result;
int.TryParse(value.ToString(), out result);
return result;
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int result;
int.TryParse(value.ToString(), out result);
return result;
}
}

Categories