chirag pathak chirag pathak - 8 months ago 109
C# Question

C# ListView : Null Reference exception, object reference not set to an instance in winforms

I want to display list of .txt files present in the folder, in listview in windows form, for that I have put a listview 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, listview 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);


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