Pregunta

I have two Forms:

  Form1
  Form2

Whenever I check/uncheck a CheckBox checkBox1 on Form2 I want to update textbox1.Readonly that is on Form1. If both textbox1 and checkbox1 had been on the same Form it would be easy go:

  private void checkBox1_CheckedChanged(object sender, EventArgs e) {
    textbox1.Readonly = checkBox1.Checked;
  }

What shall I do in my case when textbox1 and checkbox1 are on different Forms?

¿Fue útil?

Solución

You can put it like this:

public partial class Form1: Form {
  ...

  // textBox1 is private (we can't access in from Form2) 
  // so we'd rather create a public property
  // in order to have an access to textBox1.Readonly
  public Boolean IsLocked {
    get {
      return textBox1.Readonly;
    }
    set {
      textBox1.Readonly = value;
    }
  }
}

...

public partial class Form2: Form {
  ...

  private void checkBox1_CheckedChanged(object sender, EventArgs e) {
    // When checkBox1 checked state changed,
    // let's find out all Form1 instances and update their IsLocked state
    foreach (Form fm in Application.OpenForms) {
      Form1 f = fm as Form1;

      if (!Object.RefrenceEquals(f, null))
        f.IsLocked = checkBox1.Checked;
    }  

  }
}

Otros consejos

You should use events and delegates.

On Form2, We're create a delegate and event

public delegate void OnCheckedEventHandler(bool checkState);
public event OnCheckedEventHandler onCheckboxChecked;

public void checkBox1_Checked(object sender, EventArgs e)
{
    if (onCheckboxChecked != null)
        onCheckboxChecked(checkBox1.Checked);
}

And on Form1, we're realize this event:

void showForm2()
{
    Form2 f2 = new Form2();
    f2.onCheckboxChecked += onCheckboxChecked;
    f2.Show();
}

public void onCheckboxChecked(bool checkState)
{
    textBox1.ReadOnly = checkState;
}

For simplier and more flexible

Form1:

public class Form1 : System.Windows.Forms.Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
        {
        Form2 tmpFrm = new Form2();
        tmpFrm.txtboxToSetReadOnly = this.txtMyTextBox; //send the reference of the textbox you want to update
        tmpFrm.ShowDialog(); // tmpFrm.Show();
    }
}

FOrm2:

public class Form2 : System.Windows.Forms.Form
{
    public Form2()
    {
        InitializeComponent();
    }

    TextBox _txtboxToSetReadOnly = null;
    public TextBox txtboxToSetReadOnly
    {
        set{ this._txtboxToSetReadOnly = value; }
        get {return this._txtboxToSetReadOnly;}
    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
        if( this._txtboxToSetReadOnly != null)  this._txtboxToSetReadOnly.ReadOnly = checkbox1.Checked;
        /*
         or the otherway 
        if( this._txtboxToSetReadOnly != null) this._txtboxToSetReadOnly.ReadOnly = !checkbox1.Checked;
        */
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top