Get the values of fields (variables) declared in a form by their names in C#

This 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 field's name from the combo box, the program uses the following code to display the selected field's 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 instance variables 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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.