-1

Below is the code snippet of what i am trying to do.

dynamic model = new ExpandoObject();
        foreach (Control control in ConfigData.ActiveForm.Controls)
        {
            string controlType = control.GetType().ToString();
            if (controlType == "System.Windows.Forms.TextBox")
            {
                TextBox txtBox = (TextBox)control;
                if (string.IsNullOrEmpty(txtBox.Text))
                {
                    MessageBox.Show(txtBox.Name + " Can not be empty");
                    return;
                }
                model[txtBox.Name] = txtBox.Text; // this gives error
            }
          

        }

here i want to create a property with name of the value came from txtBox.name

for example if value of textBox.name="mobileNo" i want to add a property with name mobileNo to model. how to do that?

1 Answers1

2
dynamic expando = new ExpandoObject();

// Add properties dynamically to expando
AddProperty(expando, "Language", "English");

public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
{
    // ExpandoObject supports IDictionary so we can extend it like this
    var expandoDict = expando as IDictionary<string, object>;
    if (expandoDict.ContainsKey(propertyName))
        expandoDict[propertyName] = propertyValue;
    else
        expandoDict.Add(propertyName, propertyValue);
}

Thanks to Jay Hilyard and Stephen Teilhet

source: https://www.oreilly.com/content/building-c-objects-dynamically/

nilsK
  • 4,323
  • 2
  • 26
  • 40