Reputation: 1
I just want to ask if it is possible to add a method within a class in c#??
Like for example I have a form named Sample Form and then I have two textbox that the user should enter data. Then I have a button that will save the data in the textbox into the database. But before saving it in the database it should first check if the textbox has a value or not.
What I want to do is add a class and put there a function or a method that will do the checking so that I can use it in other forms also. How will I do it? Please help me. Thank you so much in advanced.
Upvotes: 0
Views: 194
Reputation: 1
You do not need to write calass to do that. TextBox class already have that.
textBox1.TextLength
if(textBox1.TextLength > 0)
MessageBox.Show("TextBox has value!");
Upvotes: 0
Reputation: 13670
You could do something basic, but you will probably always need to change it based on the scenario.
public static class FormValidator
{
public static bool IsValid<TForm>(TForm form) where TForm : Form {
if (!string.IsNullOrEmpty(form.TextBox1.Text) && !string.IsNullOrEmpty(form.TextBox2.Text)) {
return true;
}
else {
return false;
}
}
}
// example:
bool isValid = FormValidator.IsValid<MyForm>(myFormInstance);
Honestly though you should be doing per-form validation in each form that needs validated. The method in which you seek is bad design because it creates very tight coupling on validation, and if you need something custom for one form it breaks.
Plus, it sounds like you should be designing your form to handle multiple scenarios, rather than designing a validator to validate multiple forms, but I hope this at least helps you with your question and provides insight.
Good luck.
Upvotes: 3
Reputation: 96
add a button which checks the text box on click...or use the evnt handler ontext changed
Upvotes: 0