mercredi 7 décembre 2016

Can't set User Control property using Reflection, raise NullReference

I have my own User Control with WinForms DataGrid inside. Code is below

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;
            }
        }
    }
}

After Initialising my form, which contains my User Control i trying to use reflection to set DataSource property this way

Type type = ObjectName.GetType();
PropertyInfo DataSource = type.GetProperty("DataSource");
DataSource.SetValue(ObjectName, cs.table);

This code raises NullReference exception on line

DataSource.SetValue(ObjectName, cs.table);

As i can see in VS IntelliSence DataSource object have null reference and i can't resolve this problem. If i trying to use reflectio similar way for assign property value to standart WinForms control, ex. ComboBox - it works correctly, and DataSource have reference to Object.

It seems like i can't assign property this way and my UC constructor written wrong.

How can i set property to custom User Control using reflection?





Aucun commentaire:

Enregistrer un commentaire