Good morning

I have an event called "OptionChanged" that is triggered when one of many CheckBox's is changed.

string cb = ((CheckBox)sender).Name.Remove(((CheckBox)sender).Name.Count() - 1);

gets the name of the changed CheckBox, removes the last letter then copies it to a string.

Now, i need to find the relevant bool (named exactly like the string) that has already been declared to change its value.

Is this possible?

Thanks

Recommended Answers

All 4 Replies

It's possible... you'd have to use Reflection (essentially it makes the program source code aware). I would highly recommend you do not do this, as it can be very prone to bugs/errors and is generally reserved for debugging (or possibley very speciallized circumstances).

What are you trying to achieve?

Thanks for the reply mmaillet.
I am trying to lump all the events of different checkboxes into one function. I have specifically named the checkboxes and bools to enable me to do this; thus the removing of the last character.

I am just looking for a way to shorten the code from say 50 lines to around 3.

thanks again

You could accomplish your goal via Reflection something like this:

private bool fred;
public void SetBoolean(string boolToSet, bool Value)
{
    System.Reflection.FieldInfo fi = this.GetType.GetField(boolToSet, Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Public);
    fi.SetValue(this, Value);
}
public void test()
{
    SetBoolean("fred", true);
}

However, I would recommend that you consider using a Dictionary(Of String, Boolean) instead. It will give you the access by name feature that you want.

thats an awesome bit of code there TnTinMN! i got round the problem in the end but this will be very useful for me in future projects.

Thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.