Validate one method C# - c#

If I have one validating method Method1 which returns e.Cancel true or false, and which looks like this:
private void textBox1_Validating_1(object sender, CancelEventArgs e)
{
ErrorProvider errorProvider = new ErrorProvider();
bool isEmpty = String.IsNullOrEmpty(textBox1.Text);
if (isEmpty)
{
e.Cancel = true;
errorProvider.SetError(textBox1, "txt");
}
else
{
e.Cancel = false;
errorProvider.SetError(textBox1, "");
}
}
And I want to get the result of validation, in my other method, here:
private void button4_Click(object sender, EventArgs e)
{
//bool passed = this.Validate(textBox1_Validating_1);
if (passed == false) return;
I would want something like this:
bool passed = this.Validate(textBox1_Validating_1);
Only to validate this one method. How do I do it?
I am able to do it like this:
bool passed = this.ValidateChildren();
if (passed == false) return;
But if I do that, then I validate all my methods, but I one want to validate just this one Method1
How can I accomplish this?

I will suggest to create a separate method for validation and call it on submit. Try this :
private void SubmitButton_Click(object sender, EventArgs e)
{
if (ValidateControls()==0)
{
//Form is validated
}
}
int ValidateControls()
{
int flag = 0;
errorProvider1.Clear();
if (txtAge.Text.Trim() == String.Empty)
{
errorProvider1.SetError(txtAge, "Age is required");
flag = 1;
}
............................................
............................................
// validate all controls
............................................
............................................
if (txtSalary.Text.Trim() == String.Empty)
{
errorProvider1.SetError(txtSalary, "Salary is required");
flag = 1;
}
return flag;
}

public bool IsValidated()
{
return !String.IsNullOrEmpty(textBox1.Text);
}
private void button4_Click(object sender, EventArgs e)
{
bool passed = IsValidated();
}

Something like this?
var cnclEvent = new CancelEventArgs();
textBox1_Validating_1(null, cnclEvent);
if (cnclEvent.Cancel) return;

Related

cannot implicitly convert type void to int c#

Hello So I am making a text editor and have two functions I call when clicking on different buttons in my GUI. So I call my "NewTextbutton" function in "CloseToolStripMenuItem" function. What I want is if the user clicks on cancel my program should not close.I though I can have a returned value from the function and then with if statment check if the user clicked on cancel or not. But I get error that I cannot convert Void to int. Can anyone please help. Thanks.
private int NewTextbutton_Click(object sender, EventArgs e)
{
if (TextBox.TextLength==0)
{
TextBox.Clear();
return 0;
}
else
{
if (this.Text.Contains("*"))
{
var result = MessageBox.Show("Do you want to save changes to the document?",
"Texteditor",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
SaveTextbutton.PerformClick();
TextBox.Clear();
this.Text = $"Texteditor dok1.txt";
P = "";
return 0;
}
else if (result == DialogResult.Cancel)
{
return 1;
}
else
{
TextBox.Clear();
return 0;
}
}
TextBox.Clear();
this.Text = $"Texteditor dok1.txt";
P = "";
return 0;
}
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
int a = NewTextbutton.PerformClick(); //here is the error "cannot convert void to int"
if (a == 1)
{
MessageBox.Show("operation Canceled");
}
else
{
Application.Exit();
}
}
Indeed, an event handler usually returns void not int, so you cannot use PerformClick to get a return value.
You can refactor this way, for instance :
private int CheckWhatToDo()
{
// all the code that was in NewTextbutton_Click(object sender, EventArgs e)
}
private void NewTextbutton_Click(object sender, EventArgs e) {
CheckWhatToDo();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
int a = CheckWhatToDo();
if (a == 1)
{
MessageBox.Show("operation Canceled");
}
else
{
Application.Exit();
}
}

Make Button Enabled after bools are true

I need make Button active if theese three bools are true
public bool isFileOpened = false;
public bool isDrive = false;
public bool isPrice = false;
They are becoming true after two textboxes are filled and
filePath string is not empty
private void textBox1_TextChanged(object sender, EventArgs e) {
drive = CheckIntInput(sender, "not valid");
if (drive != 0) {
isDrive = true;
}
}
private void textBox2_TextChanged(object sender, EventArgs e) {
price = CheckIntInput(sender, "not valid");
if (price != 0) {
isPrice = true;
}
}
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e) {
filePath = openFileDialog1.FileName;
label1.Text = filePath;
isFileOpened = true;
}
CheckIntInput method returning number from textBox or 0 if can`t convert string to number
And how i can make something like this:
if (isFileOpened && isDrive && isPrice) {
showButton.Enabled = true;
}
I want to make button enabled immediately after all three bools becomes true, and theese three fields can be inputted in different ways, like
textbox1
textbox2
openfiledialog1
or
textbox1
openfiledialog1
textbox2
There are multiple ways to do this, I'd use a property with a backing field, like this:
public bool IsFileOpened
{
get { return _isFileOpened; }
set
{
_isFileOpened = value;
UpdateShowButton();
}
}
public bool IsDrive
{
get { return _isDrive; }
set
{
_isDrive = value;
UpdateShowButton();
}
}
public bool IsPrice
{
get { return _isPrice; }
set
{
_isPrice = value;
UpdateShowButton();
}
}
private void UpdateShowButton()
{
if (IsPrice && IsDrive && IsFileOpened)
showButton.Enabled = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
drive = CheckIntInput(sender, "not valid");
if (drive != 0)
{
IsDrive = true;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
price = CheckIntInput(sender, "not valid");
if (price != 0)
{
IsPrice = true;
}
}
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
filePath = openFileDialog1.FileName;
label1.Text = filePath;
IsFileOpened = true;
}
Actually I renamed it as well, so you have to use the properties with the capitalized starting letter. Now, everytime a property is updated, it checks wether to set the showButton enabled or not.
Here you can read more about fields and properties (with backing fields as well).

How use return between methods

In my Program I have a button click, from that onclick event I am calling one method for some textbox validation. The code is:
protected void btnupdate_Click(object sender, EventArgs e)
{
CheckValidation();
//Some other Code
}
public void CheckValidation()
{
if (txtphysi.Text.Trim() == "")
{
lblerrmsg.Visible = true;
lblerrmsg.Text = "Please Enter Physician Name";
return;
}
//Some other Code
}
Here if txtphysi.text is null then it comes into loop and use return then it came from the CheckValidation() method only and it continues in btnupdate_Click event, but here I want to stop the execution process in btnupdate_Click also. How can I do it?
It is very simple programming logic in my understanding that you need to apply here..
That is return Boolean from CheckValidation() method instead of return void so that parent function knows the state from the function's execution.
protected void btnupdate_Click(object sender, EventArgs e)
{
var flag = CheckValidation();
if(!flag)
return;
//Some other Code
}
public bool CheckValidation()
{
var flag = false; // by default flag is false
if (string.IsNullOrWhiteSpace(txtphysi.Text)) // Use string.IsNullOrWhiteSpace() method instead of Trim() == "" to comply with framework rules
{
lblerrmsg.Visible = true;
lblerrmsg.Text = "Please Enter Physician Name";
return flag;
}
//Some other Code
flag = true; // change the flag to true to continue execution
return flag;
}
To achieve this:
1) Change the return type of the CheckValidation() method to bool. In your btnupdate_Click() method do something along the lines of
if(!CheckValidation())
{
return;
}
Hope that helps.
If this is ASP.NET, which you have tagged it as, then you should perhapts use a RequiredFieldValidator (for webforms), and you could use DataAnnotations if you are using MVC: http://forums.asp.net/t/1983198.aspx?RequiredFieldValidator+in+MVC
Though answer has been already accepted, but I believe this is not good practice to put code in events. Better to use delegates for such purposes.
public class Sample
{
public Sample()
{
UpdateAction = OnUpdate;
}
Action UpdateAction = null;
private void OnUpdate()
{
//some update related stuff
}
protected void btnupdate_Click(object sender, EventArgs e)
{
CheckValidation(UpdateAction);
}
public void CheckValidation(Action action)
{
if (txtphysi.Text.Trim() == "")
{
lblerrmsg.Visible = true;
lblerrmsg.Text = "Please Enter Physician Name";
return;
}
action();
}
}
Here try this:
protected void btnupdate_Click(object sender, EventArgs e)
{
if(!CheckValidation())
{
//Some other Code
}
}
public bool CheckValidation()
{
if (string.isnullorEmpty(txtphysi.Text.Trim()) )
{
lblerrmsg.Visible = true;
lblerrmsg.Text = "Please Enter Physician Name";
return false;
}
else
{
//Some other Code
return true;
}
}

Clear All TextBoxes when Input is changed in a certain box in WinForm program

I have an application where the user enters their name and weight and it will convert the weight. I was wondering if there was a way that if the user's name input was less than 2 characters the 'calculate' button would be disabled and would re-enable when more than 2 characters. I am required to create an isValid method and when I run it my application does not disable the button.
public bool isValid (String text)
{
if (string.IsNullOrWhiteSpace(Name.Text) || Name.Text.Length < 2)
{
return false;
}
else
{
return true;
}
}
private void ValidateName()
{
while (isValid(Name.Text) == false)
{
this.ConvertBtn.Enabled = false;
}
}
Use TextChanged Event
private TextBox_TextChanged(object sender, EventArgs e)
{
TextBox myTextBox = (TextBox)sender;
this.ValidateName(myTextBox.text);
}
In this case IsValid method will be executed when any changes happened in the TextBox.
I think in your case Leave Event will be better since it will execute only when user leave a control
private void TextBox_Leave(object sender, EventArgs e)
{
TextBox myTextBox = (TextBox)sender;
this.ValidateName(myTextBox.text);
}
And change your IsValid method to use parameter passed there
public bool isValid (String text)
{
cosnt int MIN_LENGTH = 2;
if (string.IsNullOrWhiteSpace(text) == true) return false;
if (text.Length < MIN_LENGTH) return false;
return true;
}
Then you don't need a loop in the Validate method
private void ValidateName(string name)
{
this.ConvertBtn.Enabled = this.IsValid(name);
}
Use textChanged event of textbox in which name is input. From that event, you can call isValid method
Added trim() to Name.Text as scenario might be Name should not include pre and post spaces. If its no required you can remove the trim().
const int LENGTH_MIN_NAME = 2;
private void Name_TextChanged(object sender, EventArgs e)
{
this.ConvertBtn.Enabled = isValid(Name.Text.Trim());
}
public bool isValid(String text)
{
return (!(string.IsNullOrWhiteSpace(text) || text.Length <= LENGTH_MIN_NAME));
}

improve a basic login system using radio buttons

here is my code:
public bool radioButtons()
{
if (!userRadioButton.Checked && !adminRadioButton.Checked)
{
MessageBox.Show("You must select an account type");
return false;
}
else
{
return true;
}
}
now, when the username is empty, it brings up the messagebox twice?
I think what you want to implement is something like that
public bool radioButtons()
{
if (!userRadioButton.Checked && !adminRadioButton.Checked)
{
MessageBox.Show("You must select an account type");
return false;
}
else
{
return true;
}
}
and in button click event.
public void button1_Click(object sender, EventArgs e)
{
bool a = radioButtons();
if (a)
{
// a is true do what you want.
}
}
you need to change 2 things:
the radioButtons method doesn't need to accept a boolean
you should declare a first
your code should look like:
public bool radioButtons()
{
if (!userRadioButton.Checked && !adminRadioButton.Checked)
{
MessageBox.Show("You must select an account type");
return false;
}
else
{
return true;
}
}
public void button1_Click(object sender, EventArgs e)
{
if (radioButtons())
{
//Your code here
}
}

Categories

Resources