Tuesday, July 20, 2010

Concise Code to Enable/Disable WinForm Controls

Let's say you have a check box (cb1)  on a form that enables a text box (txt1)  and disables a listbox (lst1).  You can write a statement that shows this dependency on 2 lines:

  txt1.Enabled = cb1.Checked;
  lst1.Enabled = !cb1.Checked;

This works fine. However, we repeat the reference to the check box state twice.
There is a way to write the above statements on the same line:

   lst1.Enabled = !(txt1.Enabled = cb1.Checked);

Looks simple when you get it right. But it took me a few minutes to figure it out.

No comments:

Post a Comment