Showing a messagebox the moment the user clicks out of the textbox - c#

I have currently set it up such that when a button is pressed and the textbox value is incorrect, it shows a messagebox. It is ok when I am testing only one textbox but when I want to test more than 1 textbox, it becomes messy where multiple messageboxes starts appearing.
Is there a way I can set it up such that the messagebox flashes the moment the user clicks away from the textbox.
For example I am expecting the textbox text to be 'World' and the user fills in the textbox with the text "hello". After that, the use goes on to click into the next textbox. When he does that the messagebox appears.
I have conflicting thoughts on this cos user could click 'x' on the messagebox and go to click the 3rd textbox which will prompt the messagebox again causing annoyance. Would be great if I could get some advice on maybe a better way to do this.
In total I am having 3 textboxes all needing to be filled and I want to check if there is any invalid entry for each of them. I tried touchleave event but it is not working. Thanks for help.
private void Button_Click(object sender, RoutedEventArgs e)
{
name = textbox_Name.Text;
if (name != "World")
{
MessageBox.Show("Invalid Entry for name.");
}
age = textbox_age.Text;
if (age != "World")
{
MessageBox.Show("Invalid Entry for age.");
}
gender = textbox_gender.Text;
if (gender != "World")
{
MessageBox.Show("Invalid Entry for gender.");
}
}

Change the logic to something that only produces one message box when the button is clicked. You could display the issue with the input in that box, maybe if name and age are wrong you could list both problems. It just requires some extra logic somewhere. I don't know what logic you need, but below is a simple example that shows a non-specific validation error.
private void Button_Click(object sender, RoutedEventArgs e)
{
name = textbox_Name.Text;
age = textbox_age.Text;
gender = textbox_gender.Text;
if (gender != "World" || name != "World" || age!="World" )
{
MessageBox.Show("Invalid Entry.");
}
}
As far as the TextChanged event goes, I'd recommend highlighting it on TextChanged, as suggested in a comment above. It's less annoying for your users. Then you could show a single MessageBox if the user clicks the button to let them know they need to fix the red textboxes.

The easiest way would be a validation of the setter.
public string name
{ get;
set
{
if (value != "Hello")
MessageBox.Show("Blah");
else
{ name = value; }
}
}
private void button1_Click(object sender, EventArgs e)
{
name = textbox_Name.Text;
}

try using TextBox.LostFocus this way you can check each textbox after programmatically.
name = textbox_Name.Text;
age = textbox_age.Text;
gender = textbox_gender.Text;
textbox_Name.LostFocus+=delegate
{
if (name != "World")
{
MessageBox.Show("Invalid Entry for name.");
}
};
textbox_age.LostFocus+=delegate
{
if (age != "World")
{
MessageBox.Show("Invalid Entry for age.");
}
};
textbox_gender.LostFocus+=delegate
{
if (gender != "World")
{
MessageBox.Show("Invalid Entry for gender.");
}
};

Related

How to show message if none of radio button selected in c# windows application

I'm fresher and I'm trying to implement gender property logic. I have three radio buttons
male, female and others. If I not select any of the radio button it should throw me an error message. First time it is giving message but second time even I select radio button it is showing same message. Please help me on this. thanks in advance.
Here is my code.
private void btnadd_Click(object sender, EventArgs e)
{
else if (!rbmale.Checked || !rbfemale.Checked || !rbothers.Checked)
{
MessageBox.Show("Please select gender ", "Error");
return;
}
You're checking it wrong way so consider this right logic for your desired output.
private void btnadd_Click(object sender, EventArgs e)
{
if (!rbmale.Checked && !rbfemale.Checked && !rbothers.Checked)
{
MessageBox.Show("Please select gender ", "Error");
return;
}
By writing like
!rbmale.Checked || !rbfemale.Checked || !rbothers.Checked
You're checking that all radio buttons should be checked and hence it is showing you error everytime even if you check any one of the
radio button.
You should check that if none of them is checked then only it should give you error message and it is the correct logic for such functionality.
Hope it helps.
It should be like
!rbmale.Checked && !rbfemale.Checked && !rbothers.Checked
You can also write something like
if (!(rbmale.Checked || rbfemale.Checked || rbothers.Checked))
{
}
Guessing that Chirag has the answer that you are looking for but there are many ways to check if all the values are false. Here are some alternatives:
if (!rbmale.Checked & !rbfemale.Checked & !rbothers.Checked)
{
}
if (new[] {rbmale.Checked,rbfemale.Checked,rbothers.Checked}.All(x => !x))
{
}
if (!rbmale.Checked || !rbfemale.Checked || !rbothers.Checked)
{
}
else
{
MessageBox.Show("Please select gender ", "Error");
return;
}

User input validation with a foreach loop in form constructor

I'm trying to use this custom method for user input validation in text boxes. But I feel something missing in this approach. Now use cant move to next text box if the validation failed. Is this a good thing or bad thing to do?
private void textBox_Validating(object sender, CancelEventArgs e)
{
TextBox currenttb = (TextBox)sender;
if (currenttb.Text == "")
{
MessageBox.Show(string.Format("Empty field {0 }", currenttb.Name.Substring(3)));
e.Cancel = true ;
}
else
{
e.Cancel = false;
}
}
Adding the handler to the textboxes with a foreach loop in the form constructor:
foreach(TextBox tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))
{
tb.Validating += textBox_Validating;
}
How about using Error Provider, it will display exclamation if validation fail
I thought it would be a bad user experience if you popup too much message box. May be you should consider use labels to display error message beside each text box. In your programm, I can't even close the window by clicking the close button if I left the text box empty.

RepositoryItemLookupEdit new value disappears before being processed

I have a LookupEdit in the grid that needs to be able to accept new values. When I enter the new value and press "Enter" or "Tab", it saves normally via the ProcessNewValue event, however when I enter a value and click elsewhere in the grid, on another cell or just in white space, the value vanishes completely. By implementing several other events and setting breakpoints all I figured out was that the value disappears before the "CloseUp" event fires. Validating, EditValueChanged, EditValueChanging, ProcessNewValue, Closed, Leave, and even GetNotInListValue never even get called because of the empty value.
Can anyone think of some setting I haven't found yet, or any other reason why this value would disappear...And how I might stop it from happening?
Found a valid Workaround
I implemented the following 3 events, in sequence, to solve this issue. I still have no idea what caused it, or how to go about preventing it. This is a Workaround, not a solution, and should be treated as such. I end up having to manually call the ProcessNewValue method, as well as forcing the value to equal the text field, and the text field back into the value later on. Not the smoothest of operations, but it does work.
private void repPatchNum1_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
{
string surfaceSoftware = vwSurfaceSoftware.GetRowCellDisplayText(vwSurfaceSoftware.FocusedRowHandle, "SurfaceSoftware");
if (string.Compare(surfaceSoftware, SOFTWARE_CHECK, true) == 0)
{
string version = vwSurfaceSoftware.GetRowCellDisplayText(vwSurfaceSoftware.FocusedRowHandle, "Version");
if (version.ToLower().Contains(VERSION_CHECK))
{//now we are certain we are in the right place
LookUpEdit editor = sender as LookUpEdit;
if (!((RPickListCollection)((BindingSource)editor.Properties.DataSource).DataSource).OfType<RPickList>().Any(a => a.RValue.Equals(e.NewValue)))
{
repPatchNum1_ProcessNewValue(sender, new DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs(e.NewValue));
vwSurfaceSoftware.SetRowCellValue(vwSurfaceSoftware.FocusedRowHandle, colPatchNum, e.NewValue);
}
}
}
}
private void repPatchNum1_CloseUp(object sender, DevExpress.XtraEditors.Controls.CloseUpEventArgs e)
{
string surfaceSoftware = vwSurfaceSoftware.GetRowCellDisplayText(vwSurfaceSoftware.FocusedRowHandle, "SurfaceSoftware");
if (string.Compare(surfaceSoftware, SOFTWARE_CHECK, true) == 0)
{
string version = vwSurfaceSoftware.GetRowCellDisplayText(vwSurfaceSoftware.FocusedRowHandle, "Version");
if (version.ToLower().Contains(VERSION_CHECK))
{//now we are certain we are in the right place
LookUpEdit editor = sender as LookUpEdit;
if (!((RPickListCollection)((BindingSource)editor.Properties.DataSource).DataSource).OfType<RPickList>().Any(a => a.RValue.Equals(e.Value)))
{
e.Value = ((LookUpEdit)sender).Text;
}
}
}
}
private void repPatchNum1_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
string surfaceSoftware = vwSurfaceSoftware.GetRowCellDisplayText(vwSurfaceSoftware.FocusedRowHandle, "SurfaceSoftware");
if (string.Compare(surfaceSoftware, SOFTWARE_CHECK, true) == 0)
{
string version = vwSurfaceSoftware.GetRowCellDisplayText(vwSurfaceSoftware.FocusedRowHandle, "Version");
if (version.ToLower().Contains(VERSION_CHECK))
{//now we are certain we are in the right place
LookUpEdit editor = sender as LookUpEdit;
string patch = vwSurfaceSoftware.GetRowCellValue(vwSurfaceSoftware.FocusedRowHandle, colPatchNum).ToString();
if (String.IsNullOrEmpty(editor.Text) && !String.IsNullOrEmpty(patch))
{
editor.Text = vwSurfaceSoftware.GetRowCellValue(vwSurfaceSoftware.FocusedRowHandle, colPatchNum).ToString();
vwSurfaceSoftware.UpdateCurrentRow();
}
}
}
}
As to the original question: Please post an answer if you know why this might be happening or how to prevent it.
Thanks all :-)
I think I found a simpler workaround, tested on DevExpress 13.
When user presses Tab/Enter, event sequence is ProcessNewValue -> CloseUp
However if user finishes lookup by clicking somewhere else, events are reversed: CloseUp -> ProcessNewValue and entered value is lost. We can use PopupCloseMode.Immediate (specifies that the dropdown window was closed because an end-user clicked outside the editor) to detect this case, manually take entered value from editor, set it to event Value field and manually call ProcessNewValue. No need for other events.
private void myLookUp_CloseUp( object sender, CloseUpEventArgs e )
{
var lookUpEdit = sender as LookUpEdit;
if( lookUpEdit != null )
{
var enteredLookUpText = lookUpEdit.Text;
if( e.CloseMode == PopupCloseMode.Immediate )
{
e.Value = enteredLookUpText;
myLookUp_ProcessNewValue( sender, new ProcessNewValueEventArgs( enteredLookUpText ) );
}
}
// Rest of event handler
}

How can I know which object is clicked in C#?

To make sure that the user name input is valid, I added such callback method to do the verification:
Regex UserNameRE = new Regex(#"^[a-zA-Z]\w*$");
//being called when input box is not focused any more
private void UserNameInput_Leave(object sender, EventArgs e)
{
//pop up a warning when user name input is invalid
if (!UserNameRE.IsMatch(UserNameInput.Text))
{
MessageBox.Show("Invalid User Name!");
this.UserNameInput.Text = "";
this.UserNameInput.Focus();
}
}
The method will be called when user finished their inputting(the method is bounded with the event-"leaving the input box"). It works when user left a invalid User_Name and begin to enter a password.
But it also works when user click another tab, e.g. the Register tab. I don't want this happen. Because the user obviously don't wanna login anymore if he clicks "Register" tab, and my C# app shouldnot pop up a warning box and force them inputting a valid user name again.
How can the C# tell the difference of such 2 situations? It should be easy if I know which object is being clicked.
You will have source of event in object sender in UserNameInput_Leave event.
private void UserNameInput_Leave(object sender, EventArgs e)
{
//sender is source of event here
}
Here's an option:
private void UserNameInput_Leave(object sender, EventArgs e)
{
if (sender.GetType() != typeof(TextBox))
{
return;
}
TextBox tBox = (TextBox)sender;
//pop up a warning when user name input is invalid
if (!UserNameRE.IsMatch(UserNameInput.Text) && tBox.Name == UserNameInput.Name)
{
MessageBox.Show("Invalid User Name!");
this.UserNameInput.Text = "";
this.UserNameInput.Focus();
}
}
I am not sure if there's a right solution for this particular scenario here.
When you add a handler to validate your control on mouse leave, definitely it will be executed first regardless you clicked on another control within the tab or another tab itself.
This normal flow can't be ignored easily. It must be possible by hanlding the message loop yourself but the event based flow, first leave focus, and selected index change (selecting) event will be fired. I would suggest you not to disturb the flow as the validation is client side and pretty fast. Instead of messagebox, I would recommend you to use ErrorProvider and attach to the control whenever required. Also messagebox is quite disturbing and as per your code, you're forcefully making it focus to the textbox again.
How about the following code?
public partial class Form1 : Form
{
ErrorProvider errorProvider = new ErrorProvider();
public Form1()
{
InitializeComponent();
textBox1.Validating += new CancelEventHandler(textBox1_Validating);
}
private void textBox1_Leave(object sender, EventArgs e)
{
textBox1.CausesValidation = true;
}
void textBox1_Validating(object sender, CancelEventArgs e)
{
Regex UserNameRE = new Regex(#"^[a-zA-Z]\w*$");
if (!UserNameRE.IsMatch(textBox1.Text))
{
errorProvider.SetError(this.textBox1, "Invalid username");
}
}
}

Textbox validation in a Windows Form

I want to put a validation that the user always enters a value in the textbox before submiting the form. But the check that I have put allows user to enter white spaces and continue submitting the form.
So, how to put the check so that the user in not able to submit the form if there are only white spaces in the textbox.
You can make your own custom validation function. This may be very naive, but somehow it will work.
private bool WithErrors()
{
if(textBox1.Text.Trim() == String.Empty)
return true; // Returns true if no input or only space is found
if(textBox2.Text.Trim() == String.Empty)
return true;
// Other textBoxes.
return false;
}
private void buttonSubmit_Click(object sender, EventArgs e)
{
if(WithErrors())
{
// Notify user for error.
}
else
{
// Do whatever here... Submit
}
}
in NET4.0 there is a nice function
if(string.IsNullOrWhiteSpace(textBox1.Text))
{
//raise your validation exception
}
else {
//go to submit
}
It can be easily be done using error provider here is the code.Error Provider you can find in your toolbox.
private void btnsubmit_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtname.Text))
{
txtname.Focus();
errorProvider1.SetError(txtname, "Please Enter User Name");
}
if (string.IsNullOrEmpty(txtroll.Text)) {
txtroll.Focus();
errorProvider1.SetError(txtroll, "Please Enter Student Roll NO");
}
}
Here is output image

Categories