I sank most of last night looking into this and found lots of half answers that didn't quite work for my fairly common issue.
I have a Textbox that i want to save to an Integer in a Database. I need to only allow the user to enter valid integers with no spaces so that:
-14 valid
14 valid
0 valid
invalid
14.3 invalid
1-4 invalid
A14 invalid
14A invalid
"14 " (has whitespace) invalid
14 (has whitespace) invalid
1 4 (has whitespace) invalid
you get the picture. only integers.
form what iv'e found this method is the key. but I cant figure out/find the regex/alternative to validate it correctly
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
//Validation code here
}
There's no need to reinvent the wheel.
Use a control such as IntegerUpDown from the Extended WPF Toolkit
I've been using MVVM so after working through a bunch of the answers in the sugested "Sugested Answer"
the Approved answer didn't validate it correctly. and all the Regex examples failed to account for the order of the - when dealing with negatives.
But using MVVM you can make the binding "Mode=TwoWay and UpdateSourceTrigger=PropertyChanged" then it validates it's self.
wont work if you don't want two way binding, so the ideal regex solution is still to be solved.
but this solves my issue.
I use regex for this : private static readonly Regex _regex = new Regex("[^0-9]");
you can bool property for it private static bool IsTextAllowed(string text)
{
return !_regex.IsMatch(text);
}
and then call it private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsTextAllowed(e.Text);
}
Related
could you fix me with my problem?
I have got a text field in my Form. And I would like to print Date and Time in a string,I mean, where cursor is.
I got this class for this:
#include <Windows.h>
//Russian letters are okay for this
private: System::Void времяИДатаToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
SYSTEMTIME sys_t;
GetSystemTime(&sys_t);
char szFormat[] = "MMMM";
char Buffer[16];
sys_t.wMonth = 1;
GetDateFormat(LOCALE_USER_DEFAULT, 0, &sys_t, szFormat, Buffer, 256);
}
};
I would like to use MessageBox::Show() , but it isn't for my problem?
Can you give some advice for this?
Thanks.
Standard warning: While it's certainly possible to write the main body of your application in C++/CLI, or even write the GUI in C++/CLI using WinForms, it is not recommended. C++/CLI is intended for interop scenarios: where C# or other .Net code needs to interface with unmanaged C++, C++/CLI can provide the translation between the two. For primary development, it is recommended to use C# with either WinForms or WPF if you want managed code, or C++ with MFC if you want unmanaged.
OK, that said: You've got the full .Net library available to you, why not use it?
void времяИДатаToolStripMenuItem_Click(Object^ sender, EventArgs^ e)
{
DateTime now = DateTime::Now;
String^ dateString = now.ToString("MMMM");
}
Assuming your text field is called textField, use:
textField->Text = new string(Buffer);
Also, your call to
GetDateFormat(LOCALE_USER_DEFAULT, 0, &sys_t, szFormat, Buffer, 256);
Is wrong. Pass 16, not 256 as the last argument (because you declared Buffer to have 16 chars).
Short Question, is it possible to disable Characters Entry in a DataPicker so that the User is just allowed to enter numbers and dots and slashes?
Kind Regards
You could handle the PreviewTextInput event of the DatePicker something like this:
<DatePicker x:Name="dp" PreviewTextInput="DatePicker_TextChanged" />
Private Sub DatePicker_TextChanged(sender As Object, e As TextCompositionEventArgs)
If Not (Microsoft.VisualBasic.Information.IsNumeric(e.Text) Or e.Text = "." Or e.Text = "/" Or e.Text = "\") Then
e.Handled = True
End If
End Sub
Is there anyway to do this in Code behind?
Sure. Try this:
AddHandler dp.PreviewTextInput, AddressOf DatePicker_TextChanged
You're going to have to do it yourself :
<TextBox PreviewTextInput="TextBox_PreviewTextInput"/>
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if(!is_number(e.Text) && !is_dot(e.Text) && ...)
{
e.Handled = true;
}
}
Setting e.Handled = true intercepts the event and prevents the action to take place.
I would recommend using a regex instead of is_number etc... (I'm sure there are plenty of examples of regexes out there).
Note that this will not work with spacebar, you will have to use the previewkeydown event for that, and there might be some other keys that are not treated in PreviewTextInput and that would modify your Text, but I can not think of any.
EDIT :
I just saw you use VB, the code I posted is for C#, I don't know any VB but I imagine it shouldn't be that different.
I want to create 2 Textboxes (txt1, txt2) and when I write in txt1 then txt2 should reflect the same text what i typed in txt1. For ex. When we create a new Solution in Visual Studio Professional, what name we give to Project, same name appears for Solution. But if we edit solution name, link between the 2 textboxes breaks.
I do have some idea about it, to do it with textChange event or in fact many similar events, but not sure that they are the best methods.
I am using Winforms, C# 4.0, Visual Studio 2010 (if this info matters)
If my question is not clear, just make a comment I will try to elaborate.
Thanks.
With the given definition of the requirement, adding TextChanged EventHandlers is the way to go.
private void txt1_TextChanged(object sender, EventArgs e)
{
txt2.Text = txt1.Text;
}
private void txt2_TextChanged(object sender, EventArgs e)
{
txt1.Text = txt2.Text;
}
Consider adding an event handler for txt1_TextChanged and txt2_KeyPress.
txt1_TextChanged would assign txt2.Text: txt2.Text = "c:\" + txt1.Text;
txt2_KeyPress would unsubscribe txt1_TextChanged: txt1.TextChanged -= txt1_TextChanged;.
I solved it, so thought to post it here
txt1_TextChanged(obje....)
{
txt2.Text = txt1.Text;
}
txt2_TextChanged(objec...)
{
if(txt2.Focused)
{
txt1.TextChanged -= new EventHandler(txt1_TextChanged);
}
}
Hope it helps.
Using WPF has made me a fan of INotifyPropertyChanged. I like to use a helper that takes an expression and returns the name as a string (see example code below). In lots of applications I see by very proficient programmers, however, I see code that handles the strings raw (see 2nd example below). By proficient I mean MVP types who know how to use Expressions.
To me, the opportunity for having the compiler catch mistakes in addition to easy refactoring makes the Exression approach better. Is there an argument in favor of using raw strings that I am missing?
Cheers,
Berryl
Expression helper example:
public static string GetPropertyName<T>(Expression<Func<T, object>> propertyExpression)
{
Check.RequireNotNull<object>(propertyExpression, "propertyExpression");
switch (propertyExpression.Body.NodeType)
{
case ExpressionType.MemberAccess:
return (propertyExpression.Body as MemberExpression).Member.Name;
case ExpressionType.Convert:
return ((propertyExpression.Body as UnaryExpression).Operand as MemberExpression).Member.Name;
}
var msg = string.Format("Expression NodeType: '{0}' does not refer to a property and is therefore not supported",
propertyExpression.Body.NodeType);
Check.Require(false, msg);
throw new InvalidOperationException(msg);
}
Raw strings example code (in some ViewModelBase type class):
/// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG"), DebuggerStepThrough]
public void VerifyPropertyName(string propertyName) {
// Verify that the property name matches a real,
// public, instance property on this object.
if (TypeDescriptor.GetProperties(this)[propertyName] == null) {
string msg = "Invalid property name: " + propertyName;
if (ThrowOnInvalidPropertyName) throw new Exception(msg);
else Debug.Fail(msg);
}
}
/// <summary>
/// Returns whether an exception is thrown, or if a Debug.Fail() is used
/// when an invalid property name is passed to the VerifyPropertyName method.
/// The default value is false, but subclasses used by unit tests might
/// override this property's getter to return true.
/// </summary>
protected virtual bool ThrowOnInvalidPropertyName { get; private set; }
To me, the opportunity for having the compiler catch mistakes in addition to easy refactoring makes the Exression approach better. Is there an argument in favor of using raw strings that I am missing?
I agree, and personally, use the expression approach in my own code, in most cases.
However, there are two reasons I know of to avoid this:
It is less obvious, especially to less experienced .NET developers. Writing RaisePropertyChanged(() => this.MyProperty ); is not always as obvious to people as RaisePropertyChanged("MyProperty");, and doesn't match framework samples, etc.
There is some performance overhead to using expressions. Personally, I don't feel this is really that meaningful of a reason, since this is usually used in data binding scenarios (which are already slow due to reflection usage), but it is potentially a valid concern.
The benefit of using the TypeDescriptor approach is that it enables dynamic property scenarios based on ICustomTypeDescriptor implementations where the implementation can effectively create dynamic property metadata on the fly for a type that is being described. Consider a DataSet whose "properties" are determined by the result set it is populated with for example.
This is something that expressions does not provide however because it's based on actual type information (a good thing) as opposed to strings.
I wound up spending more time on this than I expected, but did find a solution that has a nice mix of safety/refactorability and performance. Good background reading and an alternate solution using reflection is here. I like Sacha Barber's solution even better (background here.
The idea is to use an expression helper for a property that will participate in change notification, but only take the hit once for it, by storing the resulting PropertyChangedEventArgs in your view model. For example:
private static PropertyChangedEventArgs mobilePhoneNumberChangeArgs =
ObservableHelper.CreateArgs<CustomerModel>(x => x.MobilePhoneNumber);
HTH,
Berryl
Stack walk is slow and lambda expression is even slower. We have solution similar to well known lambda expression but almost as fast as string literal. See
http://zamboch.blogspot.com/2011/03/raising-property-changed-fast-and-safe.html
A CallerMemberName attribute was introduced in .net 4.5
This attribute can only be attached to optional string parameters and if the parameter is not used by caller in the function call then name of the caller will be passed in the string parameter
This removes the need to specify name of property when raising the PropertyChanged event thus it works with refactoring and because the changes are done at compile time there's no difference in performance.
Below is an example of implementation and more info can be found at http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx and http://msdn.microsoft.com/en-us/library/hh534540.aspx
public class DemoCustomer : INotifyPropertyChanged
{
string _customerName
public string CustomerName
{
get { return _customerNameValue;}
set
{
if (value != _customerNameValue)
{
_customerNameValue = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
SQLServer int field. Value sometimes null.
DataAdapter fills dataset OK and can display data in DatagridView OK.
When trying to retrieve the data programmatically from the dataset the Dataset field retrieval code throws a StronglyTypedException error.
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public int curr_reading {
get {
try {
return ((int)(this[this.tableHistory.curr_readingColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'curr_reading\' in table \'History\' is DBNull.", e);
}
Got past this by checking for DBNull in the get accessor and returning null but...
When the dataset structure is modified (Still developing) my changes (unsurprisingly) are gone.
What is the best way to handle this situation?
It seems I am stuck with dealing with it at the dataset level.
Is there some sort of attribute that can tell the auto code generator to leave the changes in place?
In the typed dataset designer there is the nullvalue property.
By default its value is throw exception (hence your generated code)
You can set it to the desired default value.. ie. 0.
Then it will return 0 instead of an exception. (other code is generated)
VS2008 :This works directly in the dataset designer.
VS2005 : It only works for strings in the designer but you can directly edit the XSD an set the property msprop:nullValue="0"
Leave the auto-generated code alone. There's no way to "intercept" it getting generated so any changes you do make are guaranteed to get blown away sooner or later.
.NET (well at least the .NET 2.0 system.data bits) will not convert from DBNull into anything else. This sucks but you can't do anything about it.
Write an extension method called ToNullable() or similar: it can do this:
.
public static Nullable<T> ToNullable(this object x){
if(x == DBNull.Value)
return default(T); // return null thing
else
return (T)x;
}
then you can do
int? thing = DataRow["column"].ToNullable<int>();
The dataset will have a boolean property to indicate null.
int curr_reading = ( Iscurr_readingColumnNull) ?
<default_value> : row.curr_readingColumn;
If memory serves, you need to mark the row as being edited - using .BeginEdit() or similar - then make your edits and save the row, probably using .EndEdit() or similar. You may want to do a little bit of reading into these methods (they may be on the DataSet, DataTable or DataRow) - my memory is a little hazy.
Hope this helps at least a little bit.
if(row["curr_reading"] is DBNull){
}else{
row.curr_reading;
}