chirag pathak chirag pathak - 1 year ago 61
C# Question

C#: Null Reference exception, object reference exception while add ListView at run time

I want to display list of

files present in the folder, in
in windows form, for that I have put a
control in form and write the code as under, but it gives me

Object reference not set to an instance of an object. exception.

And when I put the line lview=new ListView() to create instance,
doesn't display any data.

int i=0;
//lview=new ListView();
ListViewItem item;
DirectoryInfo d=new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
FileInfo[] Files=d.GetFiles("*.txt");
string[] f = new string[10];
var getFileList = from fName in Files
select fName;

foreach(FileInfo FI in getFileList)
item=new ListViewItem(f);

Answer Source

As I can understand, ListView is a Ui Control, which is dragged and dropped on the Winforms, so it does get initialized in the Form_Load event - InitializeComponent method, it cannot be initialized as part of the code, as I understand with commenting out that line your code works as expected

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download