2

When I click a check box on a Windows Form, it enables a text box and sets the cursor in it ready for input. Code is relatively simple:

private void chkLatte_CheckedChanged(object sender, EventArgs e)
    {
        if(chkLatte.Checked)
        {
            txtLatte.Enabled = true;
            txtLatte.Focus();
        }
        else
        {
            txtLatte.Enabled = false;
            txtLatte.Text = "0";
        }
    }

Now, here's the rub. I have lots of these check boxes so what I want is something like this:

 public void setCheckBox(string chkName, string txtName)
    {

        if (chkName.Checked)
        {
            txtName.Enabled = true;
            txtName.Focus();
        }
        else
        {
            txtName.Enabled = false;
            txtName.Text = "0";
        }
    }

Now, I can just call the method and pass the appropriate parameters like this:

  private void chkMocha_CheckedChanged(object sender, EventArgs e)
    {
        setCheckBox(chkMocha,txtMocha);
    }

Of course, this won't work: .Checked .Enabled .Focus() etc only work with a check box object and I define chkName as a string

How should I re-write the procedure setCheckBox to overcome this problem?

Beginner
  • 129
  • 10

2 Answers2

6

And why don't you pass the object sender as it is?

I mean something like this:

public void setCheckBox(CheckBox chk, TextBox txt)
{

    if (chk.Checked)
    {
        txt.Enabled = true;
        txt.Focus();
    }
    else
    {
        txt.Enabled = false;
        txt.Text = "0";
    }
}

And casting of course:

In the designer you have something like:

private System.Windows.Forms.TextBox txtMocha;

And by this reason you will solve a lot problems.

private void chkMocha_CheckedChanged(object sender, EventArgs e)
{
    setCheckBox((CheckBox)sender, txtMocha);
}

Also, I have to say, that the code you give doesn't work... You have supposed it.

If you want pass the parameters as strings, use this:

Get a Windows Forms control by name in C#

z3nth10n
  • 2,341
  • 2
  • 25
  • 49
1

One way to solve this is to assign the same handler to all checkboxes even

checkbox1.Check += chk_CheckedChanged;
checkbox2.Check += chk_CheckedChanged;
private void chk_CheckedChanged(object sender, EventArgs e)
{
   // do your logic here
}
Jaya
  • 3,721
  • 4
  • 32
  • 48
  • This does not answer the Original question: the single handler has no way of knowing which textBox to act upon, unless the logic has a way of deducing that from the identity of the sender. Such a mechanism (e.g. a Dictionary linking CheckBoxes to TextBoxes) should be part of your solution to make it complete... – Johan Donne Sep 02 '17 at 20:12