Reputation: 89
In my form there almost 30-35 controls, some are enabled and some are disabled like spouse name is disabled if the the person is unmarried and if the user selects that they are married the control get enabled.
Initially the submit button is disabled but as soon as all enabled fields are filled I want the submit button to automatically enable itself.
I have done this code for this purpose.
if ((nametxt.Text != null) && (f_nametxt.Text != null) &&
(m_nametxt.Text != null) && (gotra_txt.Text != null) &&
(panthcb.Text != null) && (fhntext.Text != null) &&
(edulvlcb.Text != null) && (bloodcb.Text != null) &&
(MarritalStatus != null) && (s_nametxt.Text != null) &&
(s_edulvlcb.Text != null) && (s_bgcb.Text != null) &&
(ressi_addresstxt.Text != null) && (ressi_phnotxt.Text != null) &&
(mobi_notxt.Text != null) && (office_addresstxt.Text != null) &&
(occup_typetxt.Text != null) && (occup_naturecb.Text != null) &&
(office_phno1txt.Text != null) && (office_mobnotxt.Text != null))
{
submit_addbtn.Enabled = true;
}
I don't whether this is correct or not and where (at which event of form) I should do this.
Please tell me and help me.
Here is the code done keydown event of text boxes and this event is not triggering
private void mobi_notxt_KeyDown(object sender, KeyEventArgs e)
{
foreach (Control c in this.Controls)
{
TextBox txt = c as TextBox;
if (txt != null)
{
if (!(txt.Enabled && txt.Text != ""))
{
allFilled = false;
break;
}
}
}
if (allFilled)
{
submit_addbtn.Enabled = true;
}
else
{
submit_addbtn.Enabled = false;
}
}
Upvotes: 0
Views: 205
Reputation: 2579
You can loop through all your TextBox controls and check if they are enabled. If they are you check the Text property.
bool allFilled = true;
foreach (Control c in this.Controls)
{
TextBox txt = c as TextBox;
if (txt != null)
{
if (txt.Enabled && txt.Text == "")
{
allFilled = false;
break;
}
}
}
if (allFilled)
{
button1.Enabled = true;
} else
{
button1.Enabled = false;
}
As a result your allFilled boolean will be true if every enabled field contains something and false in the other case.
You can assign it on any event you like. For example on a key down event which you assign to all your Text boxes
Upvotes: 1