How to set Textbox.Enabled from false to true in TextChange?

I programmatically create Formwith two textboxes. My goal is to disable one textboxif I print something in the second and vice versa. I managed to disable the second textboxwhen the first text change textbox, but I can not figure out how to enable it when the first textbox.Text is empty.

Here is the code:

private void metaName_TextChanged(object sender,EventArgs e)
    {
        var ctrl = (Control)sender;
        var frm = ctrl.FindForm();

        TextBox metaTxt = null;
        foreach (var ctr in frm.Controls)
        {
            if (ctr is TextBox)
            {
                metaTxt = (TextBox)ctr;
                if (metaTxt.Name == "metaHTTPEquiv")
                {
                    metaTxt.Enabled = false;
                }
                else
                    if (?)
                    {

                    }
            }
        }
    }

I want to do something like this:

if(textBox3.Text == String.Empty)
        {
            textBox4.Enabled = true;
        }
        else
            if(textBox3.Text != String.Empty)
        {
            textBox4.Enabled = false;
        }
0
source share
3 answers

First set a flag to enable or disable the second control based on the contents of the metaName text field that triggers the event, then find the second text field using the Linq bit.

private void metaName_TextChanged(object sender,EventArgs e)
{
    TextBox ctrl = sender as TextBox;
    if(ctrl != null)
    {
         bool enable = !string.IsNullOrEmpty(ctrl.Text);
         TextBox secondOne = this.Controls
                       .OfType<TextBox>()
                       .FirstOrDefault(x => x.Name == "metaHTTPEquiv");
        if(secondOne != null)
           secondOne.Enabled = enable;
    }
}

, , .

+2

textchanged :

private void textBox1_TextChanged(object sender, EventArgs e)
{
    textBox2.Enabled = !(textBox1.Text.Length >= 1);
}

private void textBox2_TextChanged(object sender, EventArgs e)
{
    textBox1.Enabled = !(textBox2.Text.Length >= 1);
}

self , .

+3

Forget about management events and use data binding .

Take the following helper method

static void Bind(Control target, string targetProperty, object source, string sourceProperty, Func<object, object> expression)
{
    var binding = new Binding(targetProperty, source, sourceProperty, true, DataSourceUpdateMode.Never);
    binding.Format += (sender, e) => e.Value = expression(e.Value);
    target.DataBindings.Add(binding);
}

and just add something like this to the form load event

Bind(textBox2, "Enabled", textBox1, "Text", value => string.IsNullOrEmpty((string)value));
0
source

All Articles