I have a form, with a lot of settings pages. All the pages are the same, so I would rather just make a single form, and then pass in the name of the setting its supposed to edit. How would I do this? Lets say the form is called "ConfigForm", I want to be able to call it with something like this:
new ConfigForm("event1").Show();
Simple, this pulls up the ConfigForm, and sends the string "event1". However, knowing that I am looking for the setting "event1", how do I now access this setting? Normally to access a setting, I assume I would use something like this: (event1 is a StringCollection)
string varName = Properties.Settings.Default.passedString[3];
How do I put "event1" in a string, when event1 is stored in the variable "passedString"? In PHP, I would use something like EVAL. How would I do it in C#?
---- EDIT
Previous answers have solved the "settings" problem; but it doesn't answer the underlying question. How do you use a string passed along in a variable as a variable identifier? So if I had a string called "passedString", with the text "event1" stored in it... How would I get that to convert:
this.(passedString).Text = "test";
into
this.event1.Text = "test";
Default
inherits from SettingsBase
that has the following property:
Object this[
string propertyName
] { get; set; }
So you can use []. Don't forget to cast it to StringCollection class like below
((StringCollection)Properties.Settings.Default[passedSetting])[3]
If you want to update your StringColleciton, you can get a reference to it this way:
StringCollection collection = (StringCollection)Properties.Settings.Default[passedSetting];
collection.Add("another value");
collection[3] = "replace";
Properties.Settings.Default[passedSetting] = collection; // We'd rather call the setter.
Define a constructor in the form that you want the argument to be passed to.
public class MyForm : Form
{
protected readonly string setting;
public MyForm(string setting)
{
this.setting = setting;
}
}
// to open
(new MyForm("event1")).Show();
To get/set a setting by string key use Settings.Default.this[] indexer.
To get/set a property of a control within a form use may use this simple technique:
this.Controls["button1"].Text = "someText";
// or
this.Controls.Find("button1", true).First().Text = "someText";
And if it comes to any property of a form or any other object U may use your own special setters or at last reflection .
But avoid using reflection in such simple situation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.