Home > DeveloperSection > Forums > how to add item in listview control
Anupam Mishra

Total Post:135

Posted on    January-17-2016 10:06 PM

 C# C#  .NET 

 1 Reply(s)
 406  View(s)
Rate this:
Hi all,
i want to use list view  to display item in windows form. Please give me a suitable example to display content as dynamic.
thank you .

Anupam Mishra

Total Post:135

Posted on    January-18-2016 5:49 AM

I have a listview in C# with four columns and add an item with a specified directory (i.e. c or other drive). I have done it like this and it seems to work:

public Form1()



            listView1.View = View.Details;

            listView1.GridLines = true;

            listView1.FullRowSelect = true;

                  // for adding column in listview 

            listView1.Columns.Add("Index", 60);

            listView1.Columns.Add("File Name", 300);

            listView1.Columns.Add("Size", 100);

            listView1.Columns.Add("Readonly", 70);

            int i = 1;

              // Get all text files of specified directory to add a listview

            string[] filePaths = Directory.GetFiles(@"D:\\Anupam Mishra" "*.txt",         SearchOption.AllDirectories);

            foreach (var item in filePaths)


                long len = new FileInfo(item.ToString()).Length;

                String name = new FileInfo(item.ToString()).Name;

              // for adding item in listview 

                ListViewItem _item = new ListViewItem();

                _item.Text = i.ToString();




                 // adding item in listview






for checking the file size we create a new function BytesToString(double) as below:

It returns total size and unit of file size.


  static String BytesToString(long byteCount)


            string[] _unit = { "Byte", "KB", "MB", "GB", "TB", "PB", "EB" };

            if (byteCount == 0)

                return "0" + _unit [0];

            long bytes = Math.Abs(byteCount);

            int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));

            double num = Math.Round(bytes / Math.Pow(1024, place), 1);

            return (Math.Sign(byteCount) * num).ToString() + " "+_unit [place];


It runs where user click on the button and display current selected row data. Code as follow:

private void button1_Click(object sender, EventArgs e)


            string _filePath = null;

            string Size = null;

            string ro = null;



              // When we selected any row

                _filePath = listView1.SelectedItems[0].SubItems[1].Text;

                Size = listView1.SelectedItems[0].SubItems[2].Text;

                ro = listView1.SelectedItems[0].SubItems[3].Text;

                MessageBox.Show(_filePath + ", " + Size + ", " + ro);


            catch (Exception)


                MessageBox.Show("Please select the atleast one file");




Modified On Jan-18-2016 05:50:58 AM

Don't want to miss updates? Please click the below button!

Follow MindStick