Use getfile to define path to initialise image array - c#

I'm trying to make a button which upon being pressed will get all the images in a directory and place them in order in an array of images , I have it working so far where it can get the file paths but I cant get it working for images , any ideas ?
here is the code i'm trying to use
private void button2_Click(object sender, RoutedEventArgs e)
{
string[] filePaths =Directory.GetFiles("C:/Users/Pictures/Movements/","*.jpg");
System.Windows.Controls.Image[] Form_moves =new System.Windows.Controls.Image[12];
int i = 0;
foreach (string name in filePaths)
{
Console.WriteLine(name);
Form_moves[i] = filePaths[i] ;
i++;
}
string[] UserFilePaths = Directory.GetFiles("C:/Users/Pictures/Movements/User/", "*.jpg");
foreach (string User_Move_name in filePaths)
{
Console.WriteLine(User_Move_name);
}
}

I think I've solved it :
private void button2_Click(object sender, RoutedEventArgs e)
{
string[] filePaths = Directory.GetFiles("C:/Users/Movements/Form/","*.jpg");
string[] User_Moves_filePaths = Directory.GetFiles("C:/Users/Movements/User/", "*.jpg");
System.Drawing.Image[] Form_Move = new System.Drawing.Image[9];
System.Drawing.Image[] User_Move = new System.Drawing.Image[9];
int i = 0;
int j = 0;
foreach (string name in filePaths)
{
Console.WriteLine(name);//Kept in for testing purposes SolidBrush Image CancelEventArgs see that array is being populated in correct order
Form_Move[i] = System.Drawing.Image.FromFile(filePaths[i]);
i++;
}
foreach (string User_Move_name in User_Moves_filePaths)
{
Console.WriteLine(User_Move_name);
User_Move[j] = System.Drawing.Image.FromFile(User_Moves_filePaths[j]);
j++;
}

Related

Add List<string> to DataGridView Rows

I am new to using the DataGridView component, I've used it once before and have managed to complete this exact task but I forgot how I achieved it.
Basically I would like to read the values from a text file which is formatted like so:
line 1,
line 2,
line 3
Here is the code I currently have:
List<string> tokens = new List<string>();
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
string[] lines = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach (var line in lines)
{
using (StreamReader sr = new StreamReader(Path.GetFullPath(line)))
{
var l = sr.ReadLine();
string[] data;
while (l != null)
{
data = l.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
l = sr.ReadLine();
tokens.Add(l);
}
}
}
for (int i = 0; i < tokens.Count - 1; i++)
{
dataGridView1.Rows[i].Cells[0].Selected = true;
dataGridView1.CurrentCell.Value = tokens[i];
}
}
The current code results in the line 2 being added to the datagridview only, with nothing else.
I would like to add each line into the first column of each row, depending on how many lines are in the text file.
Hopefully this makes sense, thanks a lot!
You can try this:
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
dataGridView1.Columns.Add("Value", "Value");
var files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach ( var file in files )
{
var lines = File.ReadAllLines(Path.GetFullPath(file));
foreach ( string line in lines )
dataGridView1.Rows.Add(line.TrimEnd(','));
}
}
private void dataGridView1_DragEnter(object sender, DragEventArgs e)
{
if ( e.Data.GetDataPresent(DataFormats.FileDrop) )
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}

Showing images into a list view

I am writing a code in C# to show the unknown number of images from a specified folder into a "listview" I don't know how to get all the files present in that specific folder.
I know I have to use a loop and array but I don't know how.
Here is the code which I use to access files with the "known name of file".
It's a windows form app.
private void btnZoom_Click(object sender, EventArgs e)
{
ImageList imgs = new ImageList();
imgs.ImageSize = new Size(100, 100);
string[] paths = { };
paths = Directory.GetFiles("TestFolder");
try
{
foreach (string path in paths)
{
imgs.Images.Add(Image.FromFile(path));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
listView1.SmallImageList = imgs;
listView1.Items.Add("2",0);
}
To get all the image files you can do
IEnumerable<string> paths = Directory.GetFiles(#"Your Dir", "*.*").Where(x=>x.EndsWith(".png") || x.EndsWith(".jpg")); //add all the extensions you wish in
then you can just iterate thru the list to add them in
Here is the working code:
and the code is :
private void button1_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
imageList1.Images.Clear();
string[] pics = System.IO.Directory.GetFiles( "pics//");
listView1.View = View.SmallIcon;
listView1.SmallImageList = imageList1;
imageList1.ImageSize = new Size(64, 64);
foreach (string pic in pics)
{
imageList1.Images.Add(Image.FromFile(pic));
}
for (int j = 0; j < imageList1.Images.Count; j++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
listView1.Items.Add(item);
}
}
and at designer set this:

Why is multiple item drop not working on listbox?

I create a playlist for media player.
Follow my code:
Xaml:
<MediaElement x:Name="mePlayer" Margin="64,0,90,61" ></MediaElement>
<ListBox x:Name="listbox4" Background="Salmon" BorderBrush="Black" BorderThickness="3" Drop="listbox4_Drop" >
</ListBox>
<Button x:Name="load" Content="Load" HorizontalAlignment="Left" VerticalAlignment="Top" Width="76" Click="load_Click" Margin="184,285,0,0"/>
Xaml.cs:
private Dictionary<string, string> fileDictionary = new Dictionary<string, string>();
private void load_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.DefaultExt = ".mp3";
ofd.Filter = "All|*.*";
ofd.Multiselect = true;
Nullable<bool> result = ofd.ShowDialog();
if (result == true)
{
for (int i = 0; i < ofd.FileNames.Length; i++)
{
var filePath = ofd.FileNames[i];
var fileName = System.IO.Path.GetFileName(filePath);
fileDictionary.Add(fileName, filePath);
listbox4.Items.Add(fileName);
listbox4.SelectedItem = fileName;
}
}
}
private void listbox4_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] droppedFilePaths =
e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
for (int i = 0; i < droppedFilePaths.Length; i++)
{
var filePath = droppedFilePaths[i];
var fileName = System.IO.Path.GetFileName(filePath);
fileDictionary.Add(fileName, filePath);
listbox4.Items.Add(fileName);
listbox4.SelectedItem = fileName;
}
}
}
}
It's working single file drop but while I drop multiple file then it's not added on listbox.
Multiple loaded file is loaded but multiple file will not dropped.
How can I drop multiple file on listbox?
Since I am not able to replicate the problem you listed I currently can not help you in that regard. Though, I can help you where I see fit.
Your current Drop method has an extra loop that multiples the number of items you add to the listbox.
Your current method:
private void listbox4_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] droppedFilePaths =
e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
//if you keep this loop, you will all the dropped files for each dropped file
//therefore, if I dropped 3 files, I'd get 9 entries in the listbox
//if I dropped 4 files, I'd get 16 entries and so on...
for (int i = 0; i < droppedFilePaths.Length; i++)//this has to go
{//this has to go
var filePath = droppedFilePaths[i];//this needs to be a different variable since "i" will no longer exist
var fileName = System.IO.Path.GetFileName(filePath);
//fileDictionary.Add(fileName, filePath);
listbox4.Items.Add(fileName);
listbox4.SelectedItem = fileName;
}//this has to go
}
}
}
Refactored (using the ForEach)
private void blaze_125_listbox4_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] droppedFilePaths =
e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
var filePath = droppedFilePath;
var fileName = System.IO.Path.GetFileName(filePath);
//fileDictionary.Add(fileName, filePath);
listbox4.Items.Add(fileName);
listbox4.SelectedItem = fileName;
}
}
}
This would also work (using the ForLoop)
private void blaze_125_listbox4_Drop_anotherSpin(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] droppedFilePaths =
e.Data.GetData(DataFormats.FileDrop, true) as string[];
for (int i = 0; i < droppedFilePaths.Length; i++)
{
var filePath = droppedFilePaths[i];
var fileName = System.IO.Path.GetFileName(filePath);
//fileDictionary.Add(fileName, filePath);
listbox4.Items.Add(fileName);
listbox4.SelectedItem = fileName;
}
}
}
Slimmer
private void blaze_125_listbox4_Drop_Slimmer(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] droppedFilePaths =
e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
listbox4.Items.Add(System.IO.Path.GetFileName(droppedFilePath));
}
}
}
Using the dictionary to store items, and to update the list
Dictionary<string, string> fileDictionary = new Dictionary<string, string>();
private void blaze_125_listbox4_Drop_Slimmer(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] droppedFilePaths =
e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
//listbox4.Items.Add(System.IO.Path.GetFileName(droppedFilePath));//don't need this anymore
//Check if the file is already in the dictionary.
//Check by looking up the key, and by looking up the value too.
if (fileDictionary.ContainsKey(System.IO.Path.GetFileName(droppedFilePath)) || fileDictionary.ContainsValue(droppedFilePath))
{
//no need to add this file, it's already in the dictionary
//if you try to add a file with a KEY identical to a KEY that already exists in the dictionary,
//it will throw an exception
//A dictionary can contain the same value multiple times, but it can not contain the same key more than once.
}
else
{
//the file is not listed in the dictionary, so lets add it
fileDictionary.Add(System.IO.Path.GetFileName(droppedFilePath), droppedFilePath);
}
}
}
//Now lets call the method in charge of updating the listbox
UpdateTheListbox(fileDictionary, listbox4);
}
private void UpdateTheListbox(Dictionary<string, string> incomingDictionary, ListBox listboxToModify)
{
listboxToModify.Items.Clear();//clear all the items in the list
foreach (KeyValuePair<string, string> item in incomingDictionary)
{
listboxToModify.Items.Add(item.Key);
}
//this method should probably be optimized because if your listBox already contains a large number of items
//it may be quicker to only add the missing items, instead of reverting back to an empty list, and adding all the items to it again.
//Though I'll leave this up to you to implement. We'll be here to answer questions if you have a hard time doing it.
}
Updated method to maintain the selected item if there is a selected item
private void UpdateTheListboxMaintainExistingSelection(Dictionary<string, string> incomingDictionary, ListBox listboxToModify)
{
var preSelectedItem = listboxToModify.SelectedItem;//store the current selection
listboxToModify.Items.Clear();//clear all the items in the list
foreach (KeyValuePair<string, string> item in incomingDictionary)
{
listboxToModify.Items.Add(item.Key);
}
//this method should probably be optimized because if your listBox already contains a large number of items
//it may be quicker to only add the missing items, instead of reverting back to an empty list, and adding all the items to it again.
//Though I'll leave this up to you to implement. We'll be here to answer questions if you have a hard time doing it.
//Maintain the selected item if there was one
if (preSelectedItem != null)
{
listboxToModify.SelectedItem = preSelectedItem;
}
}
To maintain the selection or select the last item if there was no selection
private void UpdateTheListboxMaintainExistingOrSelectLastAdded(Dictionary<string, string> incomingDictionary, ListBox listboxToModify)
{
var preSelectedItem = listboxToModify.SelectedItem;//store the current selection
listboxToModify.Items.Clear();//clear all the items in the list
foreach (KeyValuePair<string, string> item in incomingDictionary)
{
listboxToModify.Items.Add(item.Key);
}
//this method should probably be optimized because if your listBox already contains a large number of items
//it may be quicker to only add the missing items, instead of reverting back to an empty list, and adding all the items to it again.
//Though I'll leave this up to you to implement. We'll be here to answer questions if you have a hard time doing it.
if (preSelectedItem != null)
{
//Maintain the selected item if there was one
listboxToModify.SelectedItem = preSelectedItem;
}
else
{
//select the last item in the listbox if nothing was pre-selected
listboxToModify.SelectedItem = listboxToModify.Items[listboxToModify.Items.Count - 1];
}
}

C#, foreach values to TextBox

From below given foreach loop I'm getting all the file names in a folder. I want to know how to put all the file names in text box. According to below code only the last file name appear in textbox.
private void btnGetFileNames_Click(object sender, EventArgs e)
{
DirectoryInfo dinf = new DirectoryInfo(tbxFileLocation.Text);
foreach (FileInfo Fi in dinf.GetFiles())
{
tbxFileList.Text=Fi.ToString();
}
}
Use a StringBuilder and append the filenames to it, Display finally
StringBuilder filenames = new StringBuilder();
foreach (FileInfo Fi in dinf.GetFiles())
{
filenames.Append(Fi.ToString());
filenames.Append(",");
}
tbxFileList.Text=filenames.ToString();
Try this :
private void btnGetFileNames_Click(object sender, EventArgs e)
{
DirectoryInfo dinf = new DirectoryInfo(tbxFileLocation.Text);
foreach (FileInfo Fi in dinf.GetFiles())
{
tbxFileList.Text+=Fi.ToString() + Environment.NewLine;
}
}

How can I get info about the list View Item selected

foreach (string imageFile in files)
{
try
{
System.Drawing.Image myImage = Image.FromFile(imageFile);
myImageList.Images.Add(myImage);
myImage.Dispose();
}
catch { }
}
for (int i = 0; i < myImageList.Images.Count; i++) //I have a list view containing images
{
ListViewItem item = new ListViewItem();
item.ImageIndex = i;
imageListView.Items.Add(item);
}
private void imageListView_Clicked(object sender, EventArgs e)
{
string myImage = imageListView.SelectedItems.ToString(); //get the name of image selected
}
Now I want to get the name of image when it is selected, something like above function of imageListView_Clicked():
But it is not working.
You should modify this part of code to put name of image to its Tag property:
foreach (string imageFile in files)
{
try
{
System.Drawing.Image myImage = Image.FromFile(imageFile);
myImage.Tag="image name for each item";//you can put for example image file name
myImageList.Images.Add(myImage);
myImage.Dispose();
}
catch { }
}
then when you want to get selected image's name you can use this code:
private void imageListView_Clicked(object sender, EventArgs e)
{
String imgName= (String)imageListView.SelectedItems[0].ImageList.Images[0].Tag;
}
i think this will work.
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (listView1.SelectedItems.Count == 1)
{
MessageBox.Show(listView1.SelectedItems[0].Text);
}
}

Categories

Resources