winforms - C# Reflection. Set TableAdapter ConnectionString -
i hope can one. i've been trying create new base class winform. want have base class go through tableadapters has on , update connection strings without adding code form. put tableadapters on form , don't worry connection string settings it's handled in base class.
the problem i'm having reflection code can find property fine can't set it. can help?
below code (updated)
public class cformws : form { public string connectionstringtouse { get; set; } public cformws() { load += cformws_load; } void cformws_load(object sender, eventargs e) { initilisetableadapters(); } private void initilisetableadapters() { var listofcomponents = enumeratecomponents(); foreach (var itemcomp in listofcomponents) { if (itemcomp.tostring().tolower().endswith("tableadapter")) { var itemcompprops = itemcomp.gettype().getruntimeproperties(); var tasqlconnection = itemcompprops.firstordefault(w => w.propertytype == typeof(system.data.sqlclient.sqlconnection)); if (tasqlconnection != null) { var property = typeof(system.data.sqlclient.sqlconnection).getproperty("connectionstring"); // how set value ? string value = "some new connection string"; var convertedproperty = convert.changetype(value, property.propertytype); // tried seting value. not working "object not match target type" property.setvalue(tasqlconnection, convertedproperty, null); //// tried using method. not working "object not match target type" //var m = property.setmethod; //parameterinfo[] parameters = m.getparameters(); //m.invoke(m, parameters); // m.invoke(this, parameters); // m.invoke(itemcomp, parameters); } } } } private ienumerable<component> enumeratecomponents() { return field in gettype().getfields(bindingflags.instance | bindingflags.public | bindingflags.nonpublic) typeof(component).isassignablefrom(field.fieldtype) let component = (component)field.getvalue(this) component != null select component; }
edit:
when setvalue
, need pass in object wish set property on.
- in first example code, passed in
itemcomp
: incorrect, sinceconnectionstring
property ofsqlconnection
property ofitemcomp
- in edited question (and original answer) pass in
tasqlconnection
. however, not object,propertyinfo
based of object - the correct way value
itemcomp
object , pass in:
property.setvalue(tasqlconnection.getvalue(itemcomp), convertedproperty, null);
original (incorrect) answer:
you're trying set connectionstring
property of itemcomp
. connectionstring not property of tableadapter
of sqlconnection
(which property of tableadapter
).
the correct way of setting property this:
property.setvalue(tasqlconnection, convertedproperty, null);
Comments
Post a Comment