我使用名为 mMember 的数据库创建了动态类,其中包含一些proeprties。我想使用此属性将数据分配给wpf中的datagrid。
private void Button_Click(object sender, RoutedEventArgs e)
{
ICodeCompiler loCompiler = new CSharpCodeProvider().CreateCompiler();
CompilerParameters loParameters = new CompilerParameters();
// Start by adding any referenced assemblies
loParameters.ReferencedAssemblies.Add("System.dll");
// Must create a fully functional assembly as a string
lcCode = @"public class mMember
{
public static int cid { get; set; }
public static string cFname { get; set; }
public static string cLname { get; set; }
public static decimal? iAge { get; set; }
public static string dpDept_Id { get; set; }
public static bool? bEnabled { get; set; }
}";
// Load the resulting assembly into memory
loParameters.GenerateInMemory = false;
// Now compile the whole thing
CompilerResults loCompiled =
loCompiler.CompileAssemblyFromSource(loParameters, lcCode);
if (loCompiled.Errors.HasErrors)
{
string lcErrorMsg = "";
lcErrorMsg = loCompiled.Errors.Count.ToString() +
" Errors:";
for (int x = 0; x < loCompiled.Errors.Count; x++)
lcErrorMsg = lcErrorMsg + "\r\nLine: " +
loCompiled.Errors[x].Line.ToString() +
" - " + loCompiled.Errors[x].ErrorText;
MessageBox.Show(lcErrorMsg + "\r\n\r\n" + lcCode,
"Compiler Demo");
return;
}
Assembly loAssembly = loCompiled.CompiledAssembly;
Type calcType = loAssembly.GetType("mMember");
// Retrieve an obj ref - generic type only
object loObject =
loAssembly.CreateInstance("mMember");
PropertyInfo numberPropertyInfo = calcType.GetProperty("cLname");
numberPropertyInfo.SetValue(loObject, "Kadam", null);
string value = (string)numberPropertyInfo.GetValue(loObject, null);
var loResult1 = loObject.GetType().GetProperty("cLname").GetValue(this, null);
MessageBox.Show(loResult1.ToString());
if (loObject == null)
{
MessageBox.Show("Couldn't load class.");
return;
}
}
现在我要创建上面动态创建的类</ strong> mMember 中提到的给定属性列表,并将此列表绑定到中的 datagrid wpf 。 我想以给定格式创建List,如订单是我的类名称,它还包含 mMember 类等属性,但是在Ready Format中类。最后我将订单绑定到datagrid。
List<Order> orders = new List<Order>();
for (int i = 0; i < dt.Rows.Count; i++)
{
orders.Add(new Order() { MB_ID =Convert .ToInt64 ( dt.Rows[i]["MB_ID"]), Name = dt.Rows[i]["MEMBER_NAME"].ToString(), ItemCount = dt.Rows[i]["MB_ID"].ToString(), CompanyId = dt.Rows[i]["COMPANY_ID"].ToString() });
}
// Set the data context
this.DataContext = orders;
现在我想为 mMember 类创建类似的列表。所以我创建了相同的实例,但它没有工作
IList list1 = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(new Type[] { loObject.GetType() }));
如何将列表数据添加到此并绑定到datagrid
答案 0 :(得分:0)
我遇到了同样的问题,并且能够在您的代码与here结合使用的情况下解决问题。列表对象本身的创建代码是正确的并且有效。之后,您需要使用动态创建的对象填充列表。你只需要创建对象,例如通过“object = Activator.CreateInstance(type)”,填充它们并用“list1.Add(object)”添加它们。