例如,我有一个DataGridView带有Blue BackgroundColor属性等的控件..有没有一种方法可以将这些属性以编程方式传递或传递给另一个DataGridView控件?
像这样的东西:
dtGrid2.Property = dtGrid1.Property; // but of course, this code is not working
Run Code Online (Sandbox Code Playgroud)
谢谢...
你需要使用反射.
您获取源控件中每个属性的引用(基于其类型),然后"获取"其值 - 将该值分配给目标控件.
这是一个粗略的例子:
private void copyControl(Control sourceControl, Control targetControl)
{
// make sure these are the same
if (sourceControl.GetType() != targetControl.GetType())
{
throw new Exception("Incorrect control types");
}
foreach (PropertyInfo sourceProperty in sourceControl.GetType().GetProperties())
{
object newValue = sourceProperty.GetValue(sourceControl, null);
MethodInfo mi = sourceProperty.GetSetMethod(true);
if (mi != null)
{
sourceProperty.SetValue(targetControl, newValue, null);
}
}
}
Run Code Online (Sandbox Code Playgroud)