Title: Get variable values by name in C#
The process for displaying variable values is somewhat convoluted, but it's not too long. The example starts by using the following code to define some private and public fields.
// Some form-level values.
private string private_value1 = "This is private value 1";
private string private_value2 = "This is private value 2";
public string public_value1 = "This is public string value 1";
public string public_value2 = "This is public string value 2";
public string[] array1 = {"A", "B", "C"};
public string[] array2 = {"1", "2", "3"};
When you select a variable's name from the combo box, the program uses the following code to display the corresponding variable value.
// Display the selected field's value.
private void cboFields_SelectedIndexChanged(object sender,
EventArgs e)
{
FieldInfo field_info =
this.GetType().GetField(cboFields.Text,
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public);
if (field_info == null)
{
lblValue.Text = "";
}
else if (field_info.FieldType.IsArray)
{
// Join the array values into a string.
string[] values = (string[])field_info.GetValue(this);
lblValue.Text = string.Join(",", values);
}
else
{
// Just convert it into a string.
lblValue.Text = field_info.GetValue(this).ToString();
}
}
This code uses the form's GetType method to get the form's type object. It uses that object's GetField method to get a FieldInfo object describing the selected field. It includes the flags Instance, NonPublic, and Public so GetField returns information about variable values that are either private or public.
If the FieldInfo object is null, the code display a string saying it couldn't find the field. If the FieldInfo is an array, the code uses the GetValue method to get the value and then casts the result into an array of strings. It concatenates the string values and displays the result.
Finally if the value is not an array, the code converts it into a string and displays it.
Download the example to experiment with it and to see additional details.
|