chirag pathak chirag pathak - 2 months ago 9
C# Question

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

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();
lview.Columns.Add("FileName");
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)
{
f[i]=FI.Name;
i++;
}
item=new ListViewItem(f);
lview.Items.Add(item);

Answer

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

Comments