How to validate textboxes before saving - c#

I got this code and what I am looking for is to validate the text boxes before saving. Now if I fill the textboxes then I clear any of them it saves anyway. How could I possibly check if the are all filled before saving? I was trying to add handlers for textchanged events but I didn't work. Any suggestion will be appreciated, cheers.
public partial class frmTrainer : Form
{
public frmTrainer()
{
InitializeComponent();
// We initialize new event handlers for the subjects textboxes
this.englishTextBox.KeyPress += new KeyPressEventHandler(englishTextBox_KeyPress);
this.mathsTextBox.KeyPress += new KeyPressEventHandler(mathsTextBox_KeyPress);
this.physicsTextBox.KeyPress += new KeyPressEventHandler(physicsTextBox_KeyPress);
}
// We create a public list for all the textbox controls in the form
public List textBoxes = new List();
private void frmTrainer_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'rCMDataSet.Students_Credentials' table. You can move, or remove it, as needed.
this.students_CredentialsTableAdapter.Fill(this.rCMDataSet.Students_Credentials);
// We initialize the List of textboxes
textBoxAdd();
}
// We create method stubs for the KeyPress event on the subjects textboxes
// to allow them receive only numeric inputs
private void englishTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("Numeric input accepted only");
}
}
private void mathsTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("Numeric input accepted only");
}
}
private void physicsTextBox_KeyPress(object sendet, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("Numeric input accepted only");
}
}
// We create a method to add each textbox to the List
private void textBoxAdd()
{
textBoxes.Add(studentIDTextBox);
textBoxes.Add(first_NameTextBox);
textBoxes.Add(last_NameTextBox);
textBoxes.Add(usernameTextBox);
textBoxes.Add(passwordTextBox);
textBoxes.Add(englishTextBox);
textBoxes.Add(mathsTextBox);
textBoxes.Add(physicsTextBox);
textBoxes.Add(trainerIDTextBox);
}
// We create a private method to validate the textboxes
private void CheckTextBox()
{
foreach(TextBox txt in textBoxes)
{
if (string.IsNullOrWhiteSpace(txt.Text))
{
MessageBox.Show("Please insert data correctly");
}
}
}
private void students_CredentialsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.CheckTextBox();
try
{
//this.Validate();
this.students_CredentialsBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.rCMDataSet);
MessageBox.Show("Data saved successfully");
}
catch(System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void toolStripExit_Click(object sender, EventArgs e)
{
// We disable the automatic validation when clicking Exit button
this.AutoValidate = AutoValidate.Disable;
// We call the method to close the application
Application.Exit();
}
private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
{
// We disable the navigation buttons to prevent any skipping errors
this.bindingNavigatorMoveFirstItem.Enabled = false;
this.bindingNavigatorMoveLastItem.Enabled = false;
this.bindingNavigatorMoveNextItem.Enabled = false;
this.bindingNavigatorMovePreviousItem.Enabled = false;
}
}
}

In your students_CredentialsBindingNavigatorSaveItem_Click event, while you do call the CheckTextBox method to "validate" your controls, you're essentially not doing anything about empty controls except to show a MessageBox. What you should do is to return a boolean on the validation method whenever an empty input is found:
private bool CheckTextBox()
{
bool isValid = true;
foreach(TextBox txt in textBoxes)
{
if (string.IsNullOrWhiteSpace(txt.Text))
{
isValid = false;
MessageBox.Show("Please insert data correctly");
break; //You only need one invalid input to prevent saving
}
}
return isValid;
}
And in your Click event, check for the return value of the method and exit the event if an invalid input is detected:
private void students_CredentialsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
if(!this.CheckTextBox()) return; //Stop executing code if there's invalid input
try
{
//this.Validate();
this.students_CredentialsBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.rCMDataSet);
MessageBox.Show("Data saved successfully");
}
catch(System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Did you try using the String.Trim method on your text box text like:
foreach(TextBox txt in textBoxes)
{
//trim whitespaces from text at both ends and might be better to operate on a string
String text = txt.ToString();
text.Trim();
if (string.IsNullOrWhiteSpace(text))
{
MessageBox.Show("Please insert data correctly");
}
}

Related

One of the Four Check box not Working in C#

I've written a code in which when one check box is clicked the others get disselected
image of buttons
3 of my check boxes are working fine byname,containing and bydate But when I try to do the same with the by category check box I get the following message.error image
This is my code
private void vieworder_Load(object sender, EventArgs e)
{
try
{
con.Open();
if (con.State == ConnectionState.Open)
{
lblstatus.Text = "Connected";
lblstatus.ForeColor = Color.Green;
}
else
{
lblstatus.Text = "Not-Connected";
lblstatus.ForeColor = Color.Red;
}
showdtgrid();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void hidecheckbox()
{
chkboxbyname.CheckState = CheckState.Unchecked;
chkboxbydate.CheckState = CheckState.Unchecked;
chkboxcontaining.CheckState = CheckState.Unchecked;
checkBox1.CheckState = CheckState.Unchecked;
}
private void chkboxbyname_CheckedChanged(object sender, EventArgs e)
{
hidecheckbox();
chkboxbyname.CheckState = CheckState.Checked;
}
private void chkboxcontaining_CheckedChanged(object sender, EventArgs e)
{
hidecheckbox();
chkboxcontaining.CheckState = CheckState.Checked;
}
private void chkboxbydate_CheckedChanged(object sender, EventArgs e)
{
hidecheckbox();
chkboxbydate.CheckState = CheckState.Checked;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
hidecheckbox();
checkBox1.CheckState = CheckState.Checked;
}
}
}
Please tell me what's wrong
At a glance, it looks like the stack overflow is directly related to the event handler for checkBox1_CheckedChanged.
It looks like that handler is calling hideCheckbox(), which in turn changes the CheckState of your checkbox to Unchecked. That would in turn fire off your event handler, and therefore create an infinite loop.
What's strange is that you claim everything is working for the other checkboxes. My guess is that those checkboxes aren't wired up to their corresponding event handlers, as they should also cause stack overflow.
Could you try removing your event handler entirely if it isn't needed? Otherwise, comment out the call to hideCheckbox()

Check if user type a single character or number in textbox c#

I already can make the login for user, so if user type their username or password wrongly in textbox, the message label that says "Invalid username or password" appear. But, i want to when user type a single character or number in textbox when the message label is appear, the message label will not visible to user (visible = false) as user already type a single character or number in textbox. But the message label didn't disappear when user type a single character or number.
This is the code:
private void CheckTextBox(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
{
label5.Visible = true;
}
else
{
label5.Visible = false;
}
}
And here is the image:
Below image is when user type wrongly (the username or password), the message label appear:
Below image is when user type a single character or number, but the message label still at there
My question is: How do i set the message label to not show when user type a single character or number in the textbox?
Any help?
Your answer will be great appreciated!
Thank you!
Problem : You have not wiredup the CheckTextBox() method for both TextBox1 and TextBox2 TextChanged Event.
Solution : in your Form_Load WireUp the CheckTextBox() method for the Textbox1 and TextBox2 TextChanged Event as below:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.TextChanged += new System.EventHandler(this.CheckTextBox);
textBox2.TextChanged += new System.EventHandler(this.CheckTextBox);
}
Suggestion : i think string.IsNullOrWhiteSpace() is more appropriate as it would also check for Whitespace in addition to null and Empty strings.
Try This:
private void CheckTextBox(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text) || string.IsNullOrWhiteSpace(textBox2.Text))
{
label5.Visible = true;
}
else
{
label5.Visible = false;
}
}
This line is checking if either textbox has information in it.
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
Change the || to && and then the label will only be shown when BOTH textboxes do not have any data.
If I understand you correctly, try this:
private void CheckTextBox(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text) && string.IsNullOrEmpty(textBox2.Text))
{
label5.Visible = true;
}
else
{
label5.Visible = false;
}
}
If you change || to && then label5 will be visible only if both textboxes are empty.
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
Try this..use && instead of ||
private void CheckTextBox(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text) && string.IsNullOrEmpty(textBox2.Text))
{
label5.Visible = true;
}
else
{
label5.Visible = false;
}
}
Check this code, Should be call this OnTextChanged="CheckTextBox" on your textbox
protected void CheckTextBox(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text) && string.IsNullOrEmpty(textBox2.Text))
{
label5.Visible = true;
}
else
{
label5.Visible = false;
}
}
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="CheckTextBox"></asp:TextBox>

C# - Highlight wrong controls when validating

I am trying to validate windows form with try catch and so far I succeeded. My goal is when someone forgot to fill the gap or put in incorrect entry, catch returns messagebox with a warning. Now I also have Validating event on every control I want to validate so when somebody leave it empty or in incorrect format it will show the error next to the control. That seems ok so far (for me, at least) but my issue is, that if user doesn't even click to one box it only shows message box, but it won't highlight wrong controls.
Below is my code:
private void createButton_Click(object sender, EventArgs e)
{
try
{
Book newBook = new Book(titleBox.Text, authBox.Text, Convert.ToInt32(yearBox.Text), Convert.ToInt32(editBox.Text), pubComboBox.Text, descBox.Text);
bookList.Add(newBook);
booklistListBox.DataSource = bookList;
}
catch (FormatException)
{
MessageBox.Show("You probably missed a gap or put in incorrect form");
}
}
and those validating events:
private void titleBox_Validating(object sender, CancelEventArgs e)
{
if (titleBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(titleBox, "Title is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(titleBox, "");
}
}
private void authBox_Validating(object sender, CancelEventArgs e)
{
if (authBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(authBox, "Author is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(authBox, "");
}
}
private void yearBox_Validating(object sender, CancelEventArgs e)
{
if (yearBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(yearBox, "Year is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(yearBox, "");
}
}
private void editBox_Validating(object sender, CancelEventArgs e)
{
if (editBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(editBox, "Edition is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(editBox, "");
}
}
private void pubComboBox_Validating(object sender, CancelEventArgs e)
{
if (pubComboBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(pubComboBox, "Publisher is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(pubComboBox, "");
}
}
private void descBox_Validating(object sender, CancelEventArgs e)
{
if (descBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(descBox, "Description is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(descBox, "");
}
}
So is there way to, I don't know, change focus or something like that, forced with pressing the create button?
Thank You
Try using ValidateChildren():
private void createButton_Click(object sender, EventArgs e)
{
bool gotIssues = this.ValidateChildren();
if (gotIssues)
{
// someone didn't validate well...
}
}
So, the issue here is that you want to have it highlight in either of two scenarios:
1) When you leave the field and its contents are invalid (empty in this case)
2) When you click the create button and the field in question has invalid contents
And so I would create a single textBox_checkIfEmpty(object sender, EventArgs e) method:
private void textBox_checkIfEmpty(object sender, EventArgs e)
{
var asTb = sender as TextBox;
if (asTb != null && asTb.Text.Trim() == String.Empty)
{
errorProvider.SetError(asTb, "I'll leave it to you to abstract the error message appropriately");
e.Cancel = true;
}
else
{
errorProvider.SetError(asTb, "");
}
}
Then, you can set this method as the handler for your Validate event on your desired required controls, and you can also call the same method from the create button's handler, looping through the required TextBox instances and executing the method on each.
UPDATE
J. Hudler's ValidateChildren solution would be a more (developer) efficient tail to mine, as opposed to looping through the desired controls. That said, if the form has many children, and you only need to validate several, it might be helpful to loop still. Just depends on your specific scenario. My only other question is whether or not ValidateChildren is infinitely recursive, or if it only goes one level down (immediate children rather than all descendants).
the event validating for control call when the mouse click on the control and then leave it from the control. In your case when the user does not click on the control it will not trigger the validating event. U can do this by making your own function and call them on creat event.
private void button1_Click(object sender, EventArgs e)
{
textBox1_Validating(sender);
}
public void textBox1_Validating(object sender)
{
MessageBox.Show("validating");
errorProvider1.SetError(textBox1, "provide");
}

Controling if condition in text change function

I want if a user type the character "a" in textbox, message box with message "Ok" displays, and then textbox should clear.But I am facing the problem that when I type "a" message "Ok" is displays and along with message "No" is also displays.But when I remove the statment of clear then all goes good. Please tell me how to overcome this problem ?
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "a")
{
textBox1.Text = "";
MessageBox.Show("Ok");
}
else
{
MessageBox.Show("No");
}
}
It's because the Text="" triggered the TextChanged one more time. Use some flag like this:
bool suppressTextChanged;
private void textBox1_TextChanged(object sender, EventArgs e) {
if(suppressTextChanged) return;
if (textBox1.Text == "a") {
suppressTextChanged = true;
textBox1.Text = "";
suppressTextChanged = false;
MessageBox.Show("Ok");
} else {
MessageBox.Show("No");
}
}
NOTE: The code above supposes you want to check against a string ("a" is just an example). If you want to check against a character. Use the KeyPress event instead.
You're using the TextChanged event of the textbox. When you change the text manually the TextChanged event runs again and this time the else expression runs.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(textBox1.Text != "")
if (textBox1.Text == "a")
{
textBox1.Text = "";
MessageBox.Show("Ok");
}
else
{
MessageBox.Show("No");
}
}
That is because when you set textBox1.Text = ""; the event textBox1_TextChanged is raised one more and there is not a letter 'a' in the textbox and therefore a messasge box with "No" is also displayed.
You need to check if the change in textBox1.Text was from the user, or from you. "No" is displayed because you change the text to something ("") that is not "a". You could keep a boolean flag that indicates whether you want to react on the change:
bool changedByCode = false;
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(changedByCode) return;
if (textBox1.Text == "a")
{
changedByCode = true;
textBox1.Text = "";
changedByCode = false;
MessageBox.Show("Ok");
}
else
{
MessageBox.Show("No");
}
}
You should handle KeyUp event
public Form1()
{
InitializeComponent();
textBox1.KeyUp+=new KeyEventHandler(textBox1_KeyUp);
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (textBox1.Text == "a")
{
textBox1.Text = "";
MessageBox.Show("Ok");
}
else
{
MessageBox.Show("No");
}
}
That's because the textBox1.Text = "" calls textBox1_TextChanged again.

ListViewItem check by user, not by program

I have a ListView with various items and a ItemCheck handler as below:
private void ListView1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == System.Windows.Forms.CheckState.Checked)
{
if (e.Index == 0)
{
ListView1.Items[1].Checked = false;
ListView1.Items[2].Checked = false;
ListView1.Items[3].Checked = false;
ListView1.Items[4].Checked = false;
ListView1.Items[5].Checked = false;
ListView1.Items[6].Checked = false;
ListView1.Items[7].Checked = false;
}
else
{
ListView1.Items[0].Checked = false;
}
}
}
Essentially the first item is "none", so when it is checked all the other items become unchecked (and vice-versa). Occasionally the program checks items in the code and I think this is causing problems. I know TreeViewEventArgs has a field called Action which is equal to TreeViewAction.Unkownif the call is coming from the program and not from the user.
Is there a way to check if a ListViewItem is being checked by a user as opposed to being checked by code?
There's no way to tell from the event arguments so you would have code for it yourself, something like
private bool raisedFromCode;
private void button2_Click(object sender, EventArgs e)
{
raisedFromCode = true;
listView1.Items[1].Checked = !listView1.Items[1].Checked;
raisedFromCode = false;
}
private void listView1_ItemCheck(object sender, ItemCheckEventArgs args)
{
if (!raisedFromCode)
MessageBox.Show("User checked");
}
Alternatively if you just don't want your logic to fire when you change the check state through code you could unsubscribe from the event handler
listView1.ItemCheck -= new ItemCheckEventHandler(this.listView1_ItemCheck);
listView1.Items[1].Checked = false;
listView1.ItemCheck += new ItemCheckEventHandler(this.listView1_ItemCheck);

Categories

Resources