Search This Blog

Thursday, July 24, 2008

Using ListView Control

Code Snippet, creating groups and assigning items to groups:
ListView lv = listView1;
ColumnHeader colHead;

colHead = new ColumnHeader();
colHead.Text = "Filename";
lv.Columns.Add(colHead);

colHead = new ColumnHeader();
colHead.Text = "Size (KB)";
lv.Columns.Add(colHead);

colHead = new ColumnHeader();
colHead.Text = "Last accessed";
lv.Columns.Add(colHead);

FolderBrowserDialog dlg = new FolderBrowserDialog();

dlg.RootFolder = Environment.SpecialFolder.MyComputer;
dlg.SelectedPath = @"e:\";
if (dlg.ShowDialog() == DialogResult.OK)
{
DirectoryInfo di = new DirectoryInfo(dlg.SelectedPath);

foreach (DirectoryInfo subdi in di.GetDirectories())
{
ListViewGroup lvg = new ListViewGroup(subdi.Name);
lvg.Name = subdi.Name;
lv.Groups.Add(lvg);
foreach (FileInfo fi in di.GetFiles())
{
ListViewItem lvi = new ListViewItem();
lvi.Text = fi.Name;
lvi.Tag = fi.FullName;
lvi.Group = lvg;

ListViewItem.ListViewSubItem lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = string.Format("{0}", fi.Length/1024);
lvi.SubItems.Add(lvsi);

lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = fi.LastAccessTime.ToShortDateString();
lvi.SubItems.Add(lvsi);

lv.Items.Add(lvi);
}
}
lv.View = View.Details;
}

No comments: