I have a strange problem. I am trying to write a function that looks at a TextBox that, if it is equal to a certain value, changes the value of a string to something else. Here is my code:
I define the string in Main:
string strDoorsOption1 = "test";
The Method is defined as:
public void optionCheck(TextBox txt, string str)
{
if (txt.Text == "0")
{
str = "+++";
}
else
{
str = "---";
}
}
I call the Method like this:
private void chkDoorsSafetyLaminated_CheckedChanged(object sender, EventArgs e)
{
checkBoxClick3(chkDoorsSafetyLaminated, txtDoorsSafety1);
optionCheck(txtDoorsSafety1, strDoorsOption1);
}
checkBoxClick3 is another Method that works as intended to change the value of a TextBox. For reference, it is defined as follows:
public void checkBoxClick3(CheckBox check, TextBox txt)
{
/* Determine the CheckState of the Checkbox */
if (check.CheckState == CheckState.Checked)
{
/* If the CheckState is Checked, then set the value to 1 */
txt.Text = "1";
}
else
{
/* If the CheckState is Unchecked, then set the value to 0 */
txt.Text = "0";
}
}
This works...:
if (txtDoorsSafety1.Text == "0")
{
strDoorsOption1 = "+++";
}
else
{
strDoorsOption1 = "---";
}
But when I call optionCheck(txtDoorsSafety1, strDoorsOption1); it acts as if the method is empty. It completely compiles with no errors or warnings, it simply does nothing.
Any help would be appreciated.
public void optionCheck(TextBox txt, string str)
Passes the string by value (just like all references), which means the later assignment does not affect the class level variable. You changed the local copy, but nothing uses it.
Instead, pass by ref:
public void optionCheck(TextBox txt, ref string str)
Called as:
optionCheck(txtDoorsSafety1, ref strDoorsOption1);
public void optionCheck(TextBox txt, string str)
The string str is passed by value, not by its reference. This means in this case, that if you change it, it will not change the string, but create a new reference. This reference is only availble inside this method.
The public void checkBoxClick3(CheckBox check, TextBox txt) works, because txt.Text is a property inside the TextBox object, this its reference is always kept even outside the method.
You can fix the first method by using the ref keyword to make it act like you want (i.e. actually pass by reference)
public void optionCheck(TextBox txt, ref string str)
which you also need to use the keyword when calling:
optionCheck(txtDoorsSafety1, ref strDoorsOption1);
Although, a more conventional approach would be to simply let the optionCheck method actually return a string instead of modifying its input:
public string optionCheck(TextBox txt, string str)
Then call like
strDoorsOption1 = optionCheck(txtDoorsSafety1, strDoorsOption1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With