I am working on a WinForms project with some repetitive tasks everyday. So I thought creating code a snippet will help me out, but it works for fixed code only.
I want t
I want to add the code once the design part is done. I define the control names like intTextboxAge. The snippet should add auto validation for all textboxes, using the function defined below.
It would be better to have CustomControls with their own Validation, this way you don't need to add code after the design part is done:
//Integer input CustomControl with validation label (pictured above)
public partial class intTextBox : UserControl
{
public bool IsValid {get;set;}
public intTextBox()
{
InitializeComponent();
this.textBox1.TextChanged += this.intTextBox_TextChanged;
}
private void intTextBox_TextChanged(object sender, EventArgs e)
{
int n;
IsValid = int.TryParse(this.textBox1.Text, out n);
label1.Visible = !IsValid;
}
}
There have to be different controls based on the control's name prefix (int, str, dou, dec)
While you can use control name prefix's I recommend creating your own UserControls by deriving off base controls and simply testing the control type:
//Decimal input UserControl
public class decTextBox : TextBox
{
public string Text
{
get {
return this.Text;
}
}
public bool IsValid()
{
decimal n;
bool isDecimal = decimal.TryParse(this.Text, out n);
return isDecimal;
}
}
....
public Control AutoCode(Control forEgTheForm)
{
//Tip: You may need to recursively call this function to check children controls are valid
foreach(var ctrl in forEgTheForm.Controls) {
if(ctrl is TextBoxBase) {
if(ctrl is decTextBox) {
decTextBox txt = ((decTextBox)ctrl);
//If its not a valid value then set a[i]=true/false or in this example return the control...
if (!txt.IsValid()) return ctrl;
}
}
}
}
I want to dynamically create a code snippet, according to control names and some condition.
If you're going to create code Snippets do it according to control types, not Control name prefix's so you dont need them to be dynamic.
...
It would be even more elegant not to have to write any Snippets or validation code. This is the ideal solution. I recommend doing this by using the right type of controls.
Textboxes are good for string, however for int's, dec's and dbl's you're better off using the NumericUpDown control. This way users will intuitively know they need to enter numbers (and wont be able to enter alphanumeric characters). After setting a couple of NumericUpDown control properties (either at design time or run time) you wont need to code in validation:
I'm not sure about the cause of the performance degradation you're encountering? Though I suggest you bind controls to a class in a class library with all the business logic so that you can Unit Test. For the front-end validation though simply validating inputs are correct as shown above is the way to go.