Can we pass object like textbox to a function? - c#

I wanna ask about winforms.
Is it possible to pass object like TextBox to a function that we can call it "Checker Validation" ?
because I'm too lazy check 1 by 1 on every textbox so I'm curious about how to check it with a function
public void checker(object)
{
if(Object.Text == ""){ Object.BackColor = Color.Red;}
else{Object.BackColor = Color.White;}
}
public void textbox_TextChanged(object sender,EventArgs e)
{
checker(object);
}
i have no idea to input the object textbox on a function #.#

You can do
public void checker(TextBox txtBox)
{
if(textbox == null)
{
return;
}
if(txtBox.Text == "")
{
txtBox.BackColor = Color.Red;
}
else
{
txtBox.BackColor = Color.White;
}
}
public void textbox_TextChanged(object sender,EventArgs e)
{
checker(sender as TextBox);
}

Yes.. basically just make the param to your function a textbox...
private void Checktext(textbox mytext)
{
if (mytext.Text=="whatever")
{ }
else
{ }
}
Thats psudo code off top of my head, but it will get you there.

Related

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));
}

Editing text of multiple textboxes with function

I`m not able to find answer.
I have several text boxes and if user enters/leaves them I check if he has changed something and the code below works.
private void txtRegNazov_Enter(object sender, EventArgs e)
{
if (txtRegNazov.Text == "n/a")
{txtRegNazov.Text = "";}
}
private void txtRegNazov_Leave(object sender, EventArgs e)
{
if (txtRegNazov.Text == "")
{txtRegNazov.Text = "n/a";}
}
I would like to create a function like
public void ClearFieldDataByEnter()
{
thisHlep.text = "";
}
public void FieldDataByleave()
{
thisHelp.text = "n/a";
}
And then in every field event would be something like:
private void txtRegNazov_Enter(object sender, EventArgs e)
{
thisHelp.Name = name of this txtBox;
ClearFieldDataByEnter();
}
This is only an easy example of what I want
... I am looking for principe ... and I`m still new to C#.
Thank you
Rember that the "sender", in this case, is the actual TextBox.
TextBox txtSender = (TextBox)sender;
You can use the sender parameter, like this:
private void txtRegNazov_Enter(object sender, EventArgs e)
{
ClearFieldDataByEnter(sender);
}
private void txtRegNazov_Leave(object sender, EventArgs e)
{
FieldDataByleave(sender);
}
public void ClearFieldDataByEnter(object text)
{
textBox = text as TextBox;
if (textbox == null)
return;
if (textbox.Text == "n/a")
{
textbox.Text = String.Empty;
}
}
public void FieldDataByleave(object text)
{
textBox = text as TextBox;
if (textbox == null)
return;
if (String.IsNullOrEmpty(textbox.Text))
{
textbox.Text = "n/a";
}
}

Validate one method 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;

Categories

Resources