Wednesday, February 25, 2009

ListView Groups - SampleCode

This example reads a directory in windows and list out all files in groups, for example I have .doc and .xls etc files in my directory it creates 2 groups and add files according to groups

• Create a windows application
• Drag and drop ListView Control on to the form
• Drag and drop FolderBrowseDialog on to the components panel
• Drag and drop a Button on to the form
• Double click on the button and add following code

private void button1_Click(object sender, EventArgs e)
{
//Opens a folder browser dialog box for selecting the directory
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
//Clear the items before adding new items
listView1.Groups.Clear();
listView1.Items.Clear();
//Get all files from selected directory
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
//loop through all the files to add to list view
foreach (string file in files)
{
listView1.ShowGroups = true;
//get file extention
string strExtn = Path.GetExtension(file);
//Check whether group is already added or not
ListViewGroup lstGroup = listView1.Groups[strExtn];
if(lstGroup == null)
{
//if not added add the new group with file type
lstGroup = new ListViewGroup(strExtn, strExtn);
listView1.Groups.Add(lstGroup);
}
//finally add list item to listview
ListViewItem lstItem = new
ListViewItem(Path.GetFileName(file), lstGroup);
listView1.Items.Add(lstItem);
}
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home