[英]Can't set User Control property using Reflection, raise NullReference
我有自己的帶有WinForms DataGrid的用戶控件。 代碼如下
public partial class SearchTextBox : UserControl
{
public SearchTextBox()
{
_grid.Visible = false;
_grid.Location = new Point(Location.X + Height, Location.Y + Width);
}
public object DataSourse
{
get { return _grid.DataSource; }
set
{
try
{
if (value is DataTable)
{
_grid.DataSource = value;
}
else
{
_grid.DataSource = value;
}
}
catch (Exception)
{
throw;
}
}
}
}
初始化包含用戶控件的表單后,我嘗試使用反射方式設置DataSource屬性
Type type = ObjectName.GetType();
PropertyInfo DataSource = type.GetProperty("DataSource");
DataSource.SetValue(ObjectName, cs.table);
此代碼在網上引發NullReference異常
DataSource.SetValue(ObjectName, cs.table);
正如我在VS中看到的,IntelliSence DataSource對象具有空引用,並且我無法解決此問題。 如果我試圖使用reflectio類似的方法為標准的WinForms控件分配屬性值,例如。 ComboBox-它可以正常工作,並且DataSource引用了Object。
看來我無法以這種方式分配屬性,而我的UC構造函數寫錯了。
如何使用反射將屬性設置為自定義用戶控件?
不是DataSourse ,而是DataSource
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.