How to Validate Form - c#

I have a windows form for a desktop app that has 7 fields,
how can I have the submit button disabled until the form validates?
I know I can validate the form when the user clicks the button, but if i have the button disabled what is the best way to call my validation method?
Using C# express 2008.

You can always call the validation method from the change event of all 7 controls. If you have bound the controls to some datasource the datasource shuld have an OnUpdated event.
private void TextBox1_Changed(object sender, EventArgs e)
{
Validate();
}
private void ComboBox2_Changed(object sender, EventArgs e)
{
Validate();
}
private void Validate()
{
if(ValidationOk())
{
Button1.Enabled = true;
}
else
{
Button1.Enabled = false;
}
}
Or maybe:
private void Validate()
{
Button1.Enabled = ValidationOk();
}

I don't know whether you have googled it but there are plenty of article going on the inter-web. Let me see :
http://www.codeproject.com/KB/miscctrl/validatingtextbox.aspx
http://msdn.microsoft.com/en-us/library/ms229603.aspx
http://msdn.microsoft.com/en-us/library/f6xht7x2.aspx
http://www.java2s.com/Code/CSharp/GUI-Windows-Form/SimpleFormValidation.htm
I hope they help.

Related

Create a login form with enable/disable button

I learned how to have a textbox and when the value is empty the button is disabled and when I enter a value in the textbox the button is enabled.
Now I want to have a login form that contains one textbox (for username) and another textbox (for password), so here I learned how to code.
But how should I write the code so that when the condition (both text boxes are empty) the button is disabled and when the condition is (both text boxes have values) the button is enabled.
Try this:
private void txtUserName_TextChanged(object sender, EventArgs e)
{
CheckFields();
}
private void txtPassword_TextChanged(object sender, EventArgs e)
{
CheckFields();
}
private void CheckFields()
{
btnLogin.Enabled = txtPassword.Text.Length == 0 || txtUserName.Text.Length == 0 ? false : true;
}
I assume that your username textbox is named, txtUserName, and your password textbox is named, txtPassword. Also the login button is named, btnLogin. I recommend setting the btnLogin enabled property to false when the form first loads. You can set that in the form's Load event:
private void Form1_Load(object sender, EventArgs e)
{
btnLogin.Enabled = false;
}
I think it would be better if you implement this logic on the client side (javascript), it is unnecessary to go to the server again and again for every text change.
you should add onclick function on username and password textboxes and implement the logic to check whether both have values then enable the button else disable it.
You should add the TextChanged event for both boxes and have it be something like this:
private void CheckTextboxes(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtUsername.Text) || string.IsNullOrWhiteSpace(txtPassword.Text))
{
button.Enabled = false;
return;
}
button.Enabled = true;
}
private void txtUsername_TextChanged(object sender, EventArgs e)
{
CheckTextboxes();
}
private void txtPassword_TextChanged(object sender, EventArgs e)
{
CheckTextboxes();
}
That way you ensure that if the user enters values on the textboxes in either order the button only enables if both have actual text written on them.

Winforms C# Disable/ Enable Button on Treenode Click

I have a treenode which displays a checklist from a SQL database. I have a method to get the selected workflows.
I want to enable the run button if a checkbox is checked and disable the button if nothing is checked and on load.
I'm not sure where to put this if statement. I have tried putting it under the run button on the click action but it is not working correctly.
Any help is appreciated.
List<WorkflowViewModel> workflowViewList = new List<WorkflowViewModel();
var workflowList = GetSelectedWrokflows();
if (workflowList.Count == 0)
{
button.enabled = false;
}
else
{
button.enabled = true;
}
One way to do this is to create a method that will do the work of determining the selected workflow items and enabling or disabling the button. By putting the code in a single method, it allows you to call it from multiple places, and if you need to change the behavior, you only have one place to make the modifications.
Then you can just call this method from the Form_Load event, and from the checked list box's ItemCheck event:
public partial class Form1 : Form
{
List<WorkflowViewModel> workflowViewList = new List<WorkflowViewModel>();
private void SetRunButtonState()
{
workflowViewList = GetSelectedWorkflows();
button.Enabled = workflowViewList.Count > 0;
}
private void Form1_Load(object sender, EventArgs e)
{
SetRunButtonState();
}
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
SetRunButtonState();
}
// Rest of class code omitted...
}

Attemping dynamic displaying a usercontrol,how to implement this?

I want utilize a custom control(ui like a button) dynamic show a tree under it when user click it.And hide tree when custom control lost focus.
how to get it ?
(In addition can't use Form control.)
Create a control(tree) which is hidden from the beginning.
yourControl.Visible = false;
Create your button and your click eventhandler
yourButton.Click += yourButton_Click;
private void yourButton_Click(object sender, EventArgs e)
{
yourControl.Visible = true;
}
To hide when focus is lost, you need to create another method/eventhandler:
yourButton.LostFocus += yourButton_LostFocus;
void yourButton_LostFocus(object sender, EventArgs e)
{
yourControl.Visible = false;
}

textbox.Focus() not working in C#

am wondering why this code fails to focus the textbox...?
private void sendEmail_btn_Click(object sender, EventArgs e)
{
String sendTo = recipientEmail_tbx.Text.Trim();
if (!IsValidEmailAddress(sendTo))
{
MessageBox.Show("Please Enter valid Email address","Cognex" MessageBoxButtons.OK, MessageBoxIcon.Error);
recipientEmail_tbx.Focus();
}
}
Use Select() instead:
recipientEmail_tbx.Select();
Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx
Add Delay some miliSec. Delay then call Focus() and Not forget to put inside Dispatcher.
Task.Delay(100).ContinueWith(_ =>
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
TextBoxNAme.Focus();
}));
});
Even I tried with lots of above solutions but none of them worked for me as am trying to focus on page load. Finally I got this solution and it worked.
private void txtBox_LayoutUpdated(object sender, EventArgs e)
{
txtBox.Focus();
}
Use the Form_Activated event handler, in conjunction with a firstActivation boolean.
private bool firstActivation = true;
private Control firstWindowsControl = null;
...
private void DynamicForm_Activated(object sender, EventArgs e)
{
if (firstActivation)
{
firstActivation = false;
bool fwcPresent = (firstWindowsControl != null);
Console.WriteLine($"DynamicForm_Activated: firstWindowControl present: {fwcPresent}");
if (fwcPresent)
{
firstWindowsControl.Focus();
}
}

Tabpage control leave

I have a tab control and 3 tabpages in it. ( C#)
if i am in tab 2, and edit a text box value
and then click tab 3, i need to validate what was enetered in the text box.
if correct i should allow to to switch to tab 3 else should remain in tab 2 it self
how do i achieve this?
iam curently handling the "leave" event of the tabpage2,
i validate the text box value there and if found invalid
i set as tabcontrol.Selectedtab = tabpage2; this does
the validation but switches to new tab! how could i restrict the navigation.
I am a novice to C#, so may be i am handling a wrong event!
Here is the relevant code:
private void tabpage2_Leave(object sender, EventArgs e)
{
if (Validatetabpage2() == -1)
{
this.tabcontrol.SelectedTab =this.tabpage2;
}
}
While the other approaches may work, the Validating event is designed specifically for this.
Here's how it works. When the SelectedIndex of the tab control changes, set the focus to the newly selected page and as well as CausesValidation = true. This ensures the Validating event will called if the user tries to leave the tab in any way.
Then do your normal validation in a page specific Validating event and cancel if required.
You need to make sure to set the initial selected tab page in the Form Shown event (Form_Load will not work) and also wire up the tab page specific validating events.
Here's an example:
private void Form_Shown(object sender, System.EventArgs e)
{
// Focus on the first tab page
tabControl1.TabPages[0].Focus();
tabControl1.TabPages[0].CausesValidation = true;
tabControl1.TabPages[0].Validating += new CancelEventHandler(Page1_Validating);
tabControl1.TabPages[1].Validating += new CancelEventHandler(Page2_Validating);
}
void Page1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text == "")
{
e.Cancel = true;
}
}
void Page2_Validating(object sender, CancelEventArgs e)
{
if (checkBox1.Checked == false)
{
e.Cancel = true;
}
}
private void tabControl1_SelectedIndexChanged(object sender, System.EventArgs e)
{
// Whenever the current tab page changes
tabControl1.TabPages[tabControl1.SelectedIndex].Focus();
tabControl1.TabPages[tabControl1.SelectedIndex].CausesValidation = true;
}
You can use the TabControl Selecting event to cancel switching pages. Setting e.Cancel to true in the event stops the tabcontrol from selecting a different tab.
private bool _cancelLeaving = false;
private void tabpage2_Leave(object sender, EventArgs e)
{
_cancelLeaving = Validatetabpage2() == -1;
}
private void tabcontrol_Selecting(object sender, TabControlCancelEventArgs e)
{
e.Cancel = _cancelLeaving;
_cancelLeaving = false;
}

Categories