1

I've a DataGridView with many rows each row contains two cells , when cell[0]= name and cell[1]= value correspond to a member in a class (also have the exact same name )

and I want to use reflection to set the properties of that class using the DataGridView like this : using question from c# - How to iterate through classes fields and set properties

GlobalParam.Params2 ParseDataGridForClass(System.Windows.Forms.DataGridView DataGrid)
{
    GlobalParam.Params2 NewSettings2 = new GlobalParam.Params2();
    foreach (System.Windows.Forms.DataGridViewRow item in DataGrid.Rows)
    {
        if (item.Cells[0].Value != null && item.Cells[1].Value != null)
        {
            Type T = NewSettings2.GetType();
            PropertyInfo info = T.GetProperty(item.Cells[0].Value.ToString());

                if (!info.CanWrite)
                continue;
            info.SetValue(NewSettings2,  
            item.Cells[1].Value.ToString(),null);
        }

    }
    return NewSettings2;
}

NewSettings look like

struct NewSettings 
{
    string a { get; set; }
    string b { get; set; }
    string c { get; set; }
}

when iterating through I see that none of the properties get's changed meaning NewSettings remains null in all of it's properties

what can be the problem ?

Community
  • 1
  • 1
LordTitiKaka
  • 2,087
  • 2
  • 31
  • 51

1 Answers1

3

First of all, your properties on the struct you provided are private, and thus the GetProperty on your struct should come back null, as it will be unable to get the private property. Secondly, structs are value types, while classes are reference types. This means that you will need to box the structure you are working with in a reference type, to keep its values. See attached working example for info. Property a made public, and the struct is boxed.

struct NewSettings
{
    public string a { get; set; }
    string b { get; set; }
    string c { get; set; }
}

This is how you would set the property.

NewSettings ns = new NewSettings();
var obj = (object)ns;
PropertyInfo pi = ns.GetType().GetProperty("a");

pi.SetValue(obj, "123");

ns = (NewSettings)obj;
Andrej Kikelj
  • 800
  • 7
  • 11