Reflection Question

Q

QQ

I am trying to access the private property of a OpenFileDialog class.

OpenFileDialog filedlg = new OpenFileDialog();

filedlg.InitialDirectory = directory.Text;

filedlg.Filter = "abc files (*.xml)|*.abc" ;
filedlg.FileName = "*.abc";
filedlg.ValidateNames = false;

if (filedlg.ShowDialog() == DialogResult.Cancel)
return;

PropertyInfo rowsPropertyInfo =
typeof(OpenFileDialog).GetProperty("fileNames",
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.GetProperty |
BindingFlags.Public |
BindingFlags.SuppressChangeType);

object[] o = (object[])rowsPropertyInfo.GetValue(filedlg,
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.GetProperty |
BindingFlags.Public |
BindingFlags.SuppressChangeType,
null, null, null);

I got an error when I tried to access the value of the property :
Error message :
An unhandled exception of type 'System.NullReferenceException' occurred in
BGReport.exe

Additional information: Object reference not set to an instance of an
object.

Can someone help ?
 
J

Jon Skeet [C# MVP]

QQ said:
I am trying to access the private property of a OpenFileDialog class.

OpenFileDialog filedlg = new OpenFileDialog();

filedlg.InitialDirectory = directory.Text;

filedlg.Filter = "abc files (*.xml)|*.abc" ;
filedlg.FileName = "*.abc";
filedlg.ValidateNames = false;

if (filedlg.ShowDialog() == DialogResult.Cancel)
return;

PropertyInfo rowsPropertyInfo =
typeof(OpenFileDialog).GetProperty("fileNames",
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.GetProperty |
BindingFlags.Public |
BindingFlags.SuppressChangeType);

object[] o = (object[])rowsPropertyInfo.GetValue(filedlg,
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.GetProperty |
BindingFlags.Public |
BindingFlags.SuppressChangeType,
null, null, null);

I got an error when I tried to access the value of the property :
Error message :
An unhandled exception of type 'System.NullReferenceException' occurred in
BGReport.exe

Additional information: Object reference not set to an instance of an
object.

Can someone help ?

Well, chances are that rowsPropertyInfo is null, which you should test
for before calling GetValue. Note that you're currently only asking for
*public* properties.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top