Treeview - Adding images files - c#

I have code and i need add to treeview only (image files) or image files higlights by other color. Do you have any ideas ? I will like for every advice. I am adding for example Download Folder, in which i have some jpeg, some avi etc. I need images with other color or add just jpeg,png and other image files.
System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
Image img = new Image();
public MainWindow()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
dlg.Description = "Vyberte složku, kterou přidat";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtbox1.Text = dlg.SelectedPath;
ListDirectory(treeView1, dlg.SelectedPath);
}
}
private void btn3_Click(object sender, RoutedEventArgs e)
{
TreeViewItem SelectedTreeViewItem = treeView1.SelectedItem as TreeViewItem;
string FileName = "";
if (SelectedTreeViewItem != null)
{
FileName = SelectedTreeViewItem.Header.ToString();
}
{
canvas1.Children.Remove(img);
img.Source = new BitmapImage(new Uri(dlg.SelectedPath + "\\" + FileName));
img.Width = 250;
img.Height = 185;
canvas1.Children.Add(img);
}
}
private void btn4_Click(object sender, RoutedEventArgs e)
{
canvas1.Children.Remove(img);
}
private void ListDirectory(TreeView treeView, string path)
{
treeView.Items.Clear();
var rootDirectoryInfo = new DirectoryInfo(path);
treeView.Items.Add(CreateDirectoryNode(rootDirectoryInfo));
}
private static TreeViewItem CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeViewItem { Header = directoryInfo.Name };
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Items.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Items.Add(new TreeViewItem { Header = file.Name});
return directoryNode;
}`

You can use LINQ to filter appropriate files:
private static TreeViewItem CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeViewItem { Header = directoryInfo.Name };
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Items.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles().Where(x=> x.Extension == ".jpg" || x.Extension == ".png"))
directoryNode.Items.Add(new TreeViewItem { Header = file.Name });
return directoryNode;
}
Following code is responsible for selection only pictures:
directoryInfo.GetFiles().Where(x=> x.Extension == ".jpg" || x.Extension == ".png")

Related

WinForms DataGridView does not respond while listing images

I have an application that allows the users to upload the selected images to the DataGridView and perform operations on their. However, when multiple images are selected, the Form freezes until the image information is uploaded to the DataGridView. I have tried BackgroundWorker for this, but it didn't work either. My codes look like this:
private void button1_Click(object sender, EventArgs e)
{
var file = new OpenFileDialog
{
Filter = #"TIFF |*.tiff| TIF|*.tif",
FilterIndex = 1,
Title = #"Select TIFF file(s)...",
Multiselect = true
};
if (file.ShowDialog() == DialogResult.OK)
{
Listing(file.FileNames);
}
}
private void Listing(string[] files)
{
foreach (var file in files)
{
var pic_name = Path.GetFileName(file);
if (file != null)
{
// Image from file
var img = Image.FromFile(file);
// Get sizes of TIFF image
var pic_sizes = img.Width + " x " + img.Height;
// Get size of TIFF image
var pic_size = new FileInfo(file).Length;
//Create the new row first and get the index of the new row
var rowIndex = dataGridView1.Rows.Add();
//Obtain a reference to the newly created DataGridViewRow
var row = dataGridView1.Rows[rowIndex];
//Now this won't fail since the row and columns exist
row.Cells["name"].Value = pic_name;
row.Cells["sizes"].Value = pic_sizes + " pixels";
row.Cells["size"].Value = pic_size + " bytes";
}
}
}
How can I solve this problem?
EDIT: After Alex's comment, I tried like this:
private void button1_Click(object sender, EventArgs e)
{
var file = new OpenFileDialog
{
Filter = #"TIFF |*.tiff| TIF|*.tif",
FilterIndex = 1,
Title = #"Select TIFF file(s)...",
Multiselect = true
};
if (file.ShowDialog() == DialogResult.OK)
{
_ = Test(file.FileNames);
}
}
private async Task Test(string[] s)
{
await Task.Run(() => Listing(s));
}
private void Listing(string[] files)
{
BeginInvoke((MethodInvoker) delegate
{
foreach (var file in files)
{
var pic_name = Path.GetFileName(file);
if (file != null)
{
// Image from file
var img = Image.FromFile(file);
// Get sizes of TIFF image
var pic_sizes = img.Width + " x " + img.Height;
// Get size of TIFF image
var pic_size = new FileInfo(file).Length;
//Create the new row first and get the index of the new row
var rowIndex = dataGridView1.Rows.Add();
//Obtain a reference to the newly created DataGridViewRow
var row = dataGridView1.Rows[rowIndex];
//Now this won't fail since the row and columns exist
row.Cells["name"].Value = pic_name;
row.Cells["sizes"].Value = pic_sizes + " pixels";
row.Cells["size"].Value = pic_size + " bytes";
}
}
});
}
But unfortunately the result is same.
I think the whole problem is in collecting image datas. Because a ready list will not take longer to load if it will not need extra processing. For this reason, I prepared a scenario like below.
private readonly BindingList<Tiff> _tiffs = new BindingList<Tiff>();
private void button1_Click(object sender, EventArgs e)
{
Listing();
}
private void Listing()
{
foreach (var f in _tiffs)
{
if (f != null)
{
var rowIndex = dataGridView1.Rows.Add();
//Obtain a reference to the newly created DataGridViewRow
var row = dataGridView1.Rows[rowIndex];
//Now this won't fail since the row and columns exist
row.Cells["ColName"].Value = f.ColName;
row.Cells["ColSizes"].Value = f.ColSizes + " pixels";
row.Cells["ColSize"].Value = f.ColSize + " bytes";
}
}
}
public static List<string> Files(string dir, string ext = "*.tiff")
{
var DirInfo = new DirectoryInfo(dir);
return DirInfo.EnumerateFiles(ext, SearchOption.TopDirectoryOnly).Select(x => x.FullName).ToList();
}
public void SetSource()
{
// Source folder of images...
var files = Files(#"___SOURCE_DIR___");
var total = files.Count;
var i = 1;
foreach (var file in files)
{
var pic_name = Path.GetFileName(file);
var img = Image.FromFile(file);
// Get sizes of TIFF image
var pic_sizes = img.Width + " x " + img.Height;
// Get size of TIFF image
var pic_size = new FileInfo(file).Length.ToString();
_tiffs.Add(new Tiff(pic_name, pic_sizes, pic_size));
BeginInvoke((MethodInvoker)delegate
{
label1.Text = $#"{i} of {total} is added to the BindingList.";
});
i++;
}
}
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
SetSource();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Set something if you want.
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Set something if you want.
}
public class Tiff
{
public Tiff(string name, string sizes, string size)
{
ColName = name;
ColSizes = sizes;
ColSize = size;
}
public string ColName { get; set; }
public string ColSizes { get; set; }
public string ColSize { get; set; }
}
And here is the result:

Unable to move files into devexpress file treelist

I have created a file treelist in my WinForms application. The files and folders are displayed in a correct way. But when I try to drag a file from my pc (for ex. from my desktop) to the application the draggednode and the target node are null. Moving folders within my application works fine. How to change my application that I can drag files into the folders in the application?
Code:
class FileListHelper
{
string rootPath;
TreeList Tree;
private DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn1;
private DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn2;
private DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn3;
private DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn4;
private DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn5;
TreeListMenu folderMenu;
public FileListHelper(TreeList tree)
{
Tree = tree;
InitColumns();
Tree.BeforeExpand += new DevExpress.XtraTreeList.BeforeExpandEventHandler(this.treeList1_BeforeExpand);
Tree.AfterExpand += new DevExpress.XtraTreeList.NodeEventHandler(this.treeList1_AfterExpand);
Tree.AfterCollapse += new DevExpress.XtraTreeList.NodeEventHandler(this.treeList1_AfterCollapse);
Tree.CalcNodeDragImageIndex += new DevExpress.XtraTreeList.CalcNodeDragImageIndexEventHandler(this.treeList1_CalcNodeDragImageIndex);
Tree.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeList1_DragDrop);
Tree.DoubleClick += new System.EventHandler(this.treeList1_DoubleClick);
Tree.PopupMenuShowing += new PopupMenuShowingEventHandler(Tree_PopupMenuShowing);
Tree.DragEnter += new DragEventHandler(this.treeList1_DragEnter); //added shows icons
tree.CellValueChanged += new CellValueChangedEventHandler(tree_CellValueChanged);
InitData();
folderMenu = new TreeListMenu(Tree);
folderMenu.Items.Add(new DXMenuItem("Create New Folder",MenuAddClick));
folderMenu.Items.Add(new DXMenuItem("Delete", MenuDeleteClick));
}
#region DragEnter
void treeList1_DragEnter(object sender,DragEventArgs e)
{
if (e.Data.GetDataPresent("FileGroupDescriptor"))
{
e.Effect = DragDropEffects.All;
}
else if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
//ensure FileGroupDescriptor is present before allowing drop
}
else if (e.Data.GetDataPresent("RenPrivateMessages"))
{
e.Effect = DragDropEffects.All;
}
else
{
e.Effect = DragDropEffects.Move;
}
}
#endregion DragEnter
#region Rename
void tree_CellValueChanged(object sender, CellValueChangedEventArgs e)
{
if (e.Column.Caption =="Name")
{
if (e.Node["Type"] == "Folder")
{
DirectoryInfo di = e.Node["Info"] as DirectoryInfo;
di.MoveTo(di.Parent.FullName+"//"+e.Value);
}
else
{
FileInfo fi = e.Node["Info"] as FileInfo;
fi.MoveTo(fi.Directory.FullName + "//" + e.Value);
}
}
}
#endregion
#region Popup Menu
void Menu_Click(object sender, EventArgs e)
{
throw new Exception("The method or operation is not implemented.");
}
void Tree_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
{
TreeListNode node = Tree.CalcHitInfo(e.Point).Node;
if (node != null)
{
e.Menu = folderMenu;
e.Menu.Tag = node;
//e.Menu.Items.Add(new DXMenuItem("Create New Folder"));
}
}
void MenuAddClick(object sender, EventArgs e)
{
DirectoryInfo di;
int ParentId = -1;
TreeListNode curentNode = folderMenu.Tag as TreeListNode;
TreeListNode folderParentNode;
if (curentNode["Type"] == "Folder")
folderParentNode = curentNode;
else
folderParentNode = curentNode.ParentNode;
if (folderParentNode == null)
{
di = new DirectoryInfo(rootPath);
}
else
{
ParentId = folderParentNode.Id;
di=folderParentNode["Info"] as DirectoryInfo;
}
DirectoryInfo newDirectory = Directory.CreateDirectory(di.FullName + "\\New Folder");
if (newDirectory != null)
{
Tree.FocusedNode = Tree.AppendNode(new object[] { newDirectory.FullName, newDirectory.Name, "Folder", null, newDirectory }, ParentId);
}
Tree.FocusedColumn = Tree.Columns["Name"];
Tree.ShowEditor();
}
void MenuDeleteClick(object sender, EventArgs e)
{
TreeListNode curentNode = folderMenu.Tag as TreeListNode;
(curentNode["Info"] as FileSystemInfo).Delete();
Tree.DeleteNode(curentNode);
}
#endregion
#region Initializing TreeList
void InitColumns()
{
this.treeListColumn1 = new DevExpress.XtraTreeList.Columns.TreeListColumn();
this.treeListColumn2 = new DevExpress.XtraTreeList.Columns.TreeListColumn();
this.treeListColumn3 = new DevExpress.XtraTreeList.Columns.TreeListColumn();
this.treeListColumn4 = new DevExpress.XtraTreeList.Columns.TreeListColumn();
this.treeListColumn5 = new DevExpress.XtraTreeList.Columns.TreeListColumn();
this.treeListColumn1.Caption = "FullName";
this.treeListColumn1.FieldName = "FullName";
this.treeListColumn2.Caption = "Name";
this.treeListColumn2.FieldName = "Name";
this.treeListColumn2.VisibleIndex = 0;
this.treeListColumn2.Visible = true;
this.treeListColumn2.SortOrder = SortOrder.Ascending;
this.treeListColumn2.SortIndex = 1;
this.treeListColumn3.Caption = "Type";
this.treeListColumn3.FieldName = "Type";
this.treeListColumn3.VisibleIndex = 1;
this.treeListColumn3.Visible = true;
this.treeListColumn3.SortOrder = SortOrder.Descending;
this.treeListColumn3.SortIndex = 0;
this.treeListColumn3.OptionsColumn.AllowEdit = false;
this.treeListColumn4.AppearanceCell.Options.UseTextOptions = true;
this.treeListColumn4.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
this.treeListColumn4.Caption = "Size(Bytes)";
this.treeListColumn4.FieldName = "Size";
this.treeListColumn4.VisibleIndex = 2;
this.treeListColumn4.Visible = true;
this.treeListColumn4.OptionsColumn.AllowEdit = false;
this.treeListColumn5.Caption = "treeListColumn5";
this.treeListColumn5.FieldName = "Info";
this.treeListColumn5.Name = "treeListColumn5";
Tree.Columns.AddRange(new DevExpress.XtraTreeList.Columns.TreeListColumn[] {
this.treeListColumn1,
this.treeListColumn2,
this.treeListColumn3,
this.treeListColumn4,
this.treeListColumn5});
}
private void InitData()
{
//int currentIncidentId=2;
//rootPath = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());
rootPath = "C:\\Data\\98-ProgrammData\\Maintenance\\Dossier\\"/*+currentIncidentId*/;
InitFolders(rootPath, null);
}
private void InitFolders(string path, TreeListNode pNode)
{
Tree.BeginUnboundLoad();
TreeListNode node;
DirectoryInfo di;
try
{
string[] root = Directory.GetDirectories(path);
foreach (string s in root)
{
try
{
di = new DirectoryInfo(s);
node = Tree.AppendNode(new object[] { s, di.Name, "Folder", null, di }, pNode);
node.StateImageIndex = 0;
node.HasChildren = HasFiles(s);
if (node.HasChildren)
node.Tag = true;
}
catch { }
}
}
catch { }
InitFiles(path, pNode);
Tree.EndUnboundLoad();
}
private void InitFiles(string path, TreeListNode pNode)
{
TreeListNode node;
FileInfo fi;
try
{
string[] root = Directory.GetFiles(path);
foreach (string s in root)
{
fi = new FileInfo(s);
node = Tree.AppendNode(new object[] { s, fi.Name, "File", fi.Length, fi }, pNode);
node.StateImageIndex = 1;
node.HasChildren = false;
}
}
catch { }
}
private void treeList1_FilterNode(object sender, DevExpress.XtraTreeList.FilterNodeEventArgs e)
{
TreeList tree = sender as TreeList;
if (string.IsNullOrEmpty(tree.FindFilterText)) return;
e.Node.Visible = IsNodeVisible(e.Node);
e.Handled = true;
}
private bool IsNodeVisible(TreeListNode node)
{
if (node.ParentNode == null)
{
foreach (TreeListColumn column in node.TreeList.VisibleColumns)
{
object val = node[column.FieldName];
if (val != null && val.ToString().ToUpper().Equals(node.TreeList.FindFilterText.ToUpper()))
return true;
}
return false;
}
return IsNodeVisible(node.ParentNode);
}
private bool HasFiles(string path)
{
string[] root = Directory.GetFiles(path);
if (root.Length > 0) return true;
root = Directory.GetDirectories(path);
if (root.Length > 0) return true;
return false;
}
private void treeList1_BeforeExpand(object sender, DevExpress.XtraTreeList.BeforeExpandEventArgs e)
{
if (e.Node.Tag != null)
{
Cursor currentCursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
InitFolders(e.Node.GetDisplayText("FullName"), e.Node);
e.Node.Tag = null;
Cursor.Current = currentCursor;
}
}
private void treeList1_AfterExpand(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
{
if (e.Node.StateImageIndex != 1) e.Node.StateImageIndex = 2;
}
private void treeList1_AfterCollapse(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
{
if (e.Node.StateImageIndex != 1) e.Node.StateImageIndex = 0;
}
#endregion
#region Dragging
private void treeList1_CalcNodeDragImageIndex(object sender, DevExpress.XtraTreeList.CalcNodeDragImageIndexEventArgs e)
{
if (e.Node[treeListColumn3].ToString() == "Folder")
{
e.ImageIndex = 0;
}
if (e.Node[treeListColumn3].ToString() == "File")
{
if (e.Node.ParentNode == Tree.FocusedNode.ParentNode)
{
e.ImageIndex = -1;
return;
}
if (e.ImageIndex == 0)
if (e.Node.Id > Tree.FocusedNode.Id)
e.ImageIndex = 2;
else
e.ImageIndex = 1;
}
}
private void treeList1_DragDrop(object sender, DragEventArgs e)
{
TreeListNode draggedNode = e.Data.GetData(typeof(TreeListNode)) as TreeListNode;
TreeListNode tagretNode = Tree.ViewInfo.GetHitTest(Tree.PointToClient(new Point(e.X, e.Y))).Node;
if (tagretNode == null || draggedNode == null) return;
if (tagretNode[treeListColumn3].ToString() == "File")
{
if (tagretNode.ParentNode == draggedNode.ParentNode)
return;
MoveInFolder(draggedNode, tagretNode.ParentNode);
}
else
{
MoveInFolder(draggedNode, tagretNode);
}
e.Effect = DragDropEffects.None;
}
void MoveInFolder(TreeListNode sourceNode, TreeListNode destNode)
{
Tree.MoveNode(sourceNode, destNode);
if (sourceNode == null) return;
FileSystemInfo sourceInfo = sourceNode[treeListColumn5] as FileSystemInfo;
string sourcePath = sourceInfo.FullName;
string destPath;
if (destNode == null)
destPath = rootPath + sourceInfo.Name;
else
{
DirectoryInfo destInfo = destNode[treeListColumn5] as DirectoryInfo;
destPath = destInfo.FullName + "\\" + sourceInfo.Name;
}
if (sourceInfo is DirectoryInfo)
Directory.Move(sourcePath, destPath);
else
File.Move(sourcePath, destPath);
sourceNode[treeListColumn5] = new DirectoryInfo(destPath);
}
#endregion
#region Executing
private void treeList1_DoubleClick(object sender, EventArgs e)
{
if ((sender as TreeList).FocusedNode[treeListColumn3].ToString() == "File")
Process.Start(((sender as TreeList).FocusedNode[treeListColumn5] as FileSystemInfo).FullName, null);
}
#endregion
}
These two lines are null:
TreeListNode draggedNode = e.Data.GetData(typeof(TreeListNode)) as TreeListNode;
TreeListNode tagretNode = Tree.ViewInfo.GetHitTest(Tree.PointToClient(new Point(e.X, e.Y))).Node;
How to fix this?

Show selected text file from one listbox in another

This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
FileInfo SelectedFileInfo = (FileInfo)ListBox1.SelectedItem;
StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
string CurrentLine = "";
//int LineCount = 0;
while(FileRead.Peek() != -1)
{
CurrentLine = FileRead.ReadLine();
//LineCount++;
//if(LineCount % 5 == 2)
{
ListBox2.Items.Add(CurrentLine);
}
}
FileRead.Close();
}
but throws exception about:
Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'System.IO.FileInfo'
When populating the listbox, use the filename instead instead the FileInfo
Then when in Button1_Click, use ListBox1.SelectedValue to get the selected file name
protected void Button1_Click(object sender, EventArgs e)
{
ListBox2.Items.Clear();
if (ListBox1.SelectedIndex > -1)
{
string filename = ListBox1.SelectedValue;
StreamReader FileRead = new StreamReader(filename);
string CurrentLine = "";
//int LineCount = 0;
while (FileRead.Peek() != -1)
{
CurrentLine = FileRead.ReadLine();
ListBox2.Items.Add(CurrentLine);
}
FileRead.Close();
}
else
{
ListBox2.Items.Add("Please select a file first");
}
}
protected void Btn_Load_Click(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\errorlog");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
ListBox1.Items.Add(file.FullName);
}
}
}

Display only image file extensions within a Listbox

Is it possible to display a listbox content, with only certain files that have a certain format? like BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff only these files with these extensions that I want to display within the lstFiles listbox.
I have tried,
lstFiles.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff";
But this did not work, is it possible?
EDIT:
I have three joint listboxes to display the system drive, folders and its content
private void lstDrive_SelectedIndexChanged_1(object sender, EventArgs e)
{
lstFolders.Items.Clear();
try
{
DriveInfo drive = (DriveInfo)lstDrive.SelectedItem;
foreach (DirectoryInfo dirInfo in drive.RootDirectory.GetDirectories())
lstFolders.Items.Add(dirInfo);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void lstFolders_SelectedIndexChanged_1(object sender, EventArgs e)
{
lstFiles.Items.Clear();
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles())
lstFiles.Items.Add(fi);
}
private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(((FileInfo)lstFiles.SelectedItem).FullName);
}
private int lastIndex = 0;
private void lstFiles_KeyUp(object sender, KeyEventArgs e)
{
if (lstFiles.SelectedIndex == lastIndex)
{
if (e.KeyCode == Keys.Up)
{
lstFiles.SelectedIndex = lstFiles.Items.Count - 1;
}
if (e.KeyCode == Keys.Down)
{
lstFiles.SelectedIndex = 0;
}
}
lastIndex = lstFiles.SelectedIndex;
}
}
}
You are population the listbox yourself using a FileInfo object. FileInfo has a property Extension. You can use that one for filtering:
private void lstFolders_SelectedIndexChanged_1(object sender, EventArgs e)
{
lstFiles.Items.Clear();
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles())
switch(fi.Extension.ToUpperInvariant())
{
case ".BMP":
case ".JPG":
...
lstFiles.Items.Add(fi);
break;
}
}
Ok, I personaly have no idea nor have ever heard of using "filter" on a list box. Why don't you just add the items you want when you have the list?
lstFiles.Items.Clear();
List<string> allowedExtensions = new List<string>() {".jpg", ".png", ".gif"};
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles().Where((x)=>allowedExtensions.Contains(x)))
{
lstFiles.Items.Add(fi);
}

Listview without an Image list?

once again i have a problem that i can't quite seem to come up with a solution to. so here it is, I have a ListView displaying the directories of Image files,i want the listview to display these images for these files, the problem is I also need the images to be modified by the program at a per-pixel level so i have this done on a separate thread, so what i want to do is take my already existing PictureBox list of the modified Images and match up the names of the files with the corresponding image. Any ideas on how to do this?
here is what i have so far
public static List<PictureBox> ContentItems = new List<PictureBox>();
...
public static string ContentDirectory = "";
private void FileTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeNode newSelected = e.Node;
FileList.Items.Clear();
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
ListViewItem.ListViewSubItem[] subItems;
ListViewItem item = null;
foreach (FileInfo file in nodeDirInfo.GetFiles())
{
item = new ListViewItem(file.Name);
subItems = new ListViewItem.ListViewSubItem[]
{ new ListViewItem.ListViewSubItem(item, "File"),
new ListViewItem.ListViewSubItem(item,
file.LastAccessTime.ToShortDateString())};
item.SubItems.AddRange(subItems);
FileList.Items.Add(item);
}
FileList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
}
I Did have to use an image list after all Heres how i got it to work:
void FileTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeNode newSelected = e.Node;
FileList.Items.Clear();
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
ListViewItem.ListViewSubItem[] subItems;
ListViewItem item = null;
ContentImg.Images.Clear();
int CurrentImg = 0;
foreach (FileInfo file in nodeDirInfo.GetFiles())
{
string fileName = file.Name;
foreach (PictureBox PB in ContentItems)
{
if (fileName == PB.Name)
{
//Get Image
ContentImg.Images.Add(PB.Image);
item = new ListViewItem(file.Name, CurrentImg);
subItems = new ListViewItem.ListViewSubItem[]
{ new ListViewItem.ListViewSubItem(item, "File"),
new ListViewItem.ListViewSubItem(item,
file.LastAccessTime.ToShortDateString())};
item.SubItems.AddRange(subItems);
FileList.Items.Add(item);
CurrentImg += 1;
}
}
}

Categories