Open image from listbox file name C# winform - c#

I have been working on this in my spare time, to no avail. I really could use a hand getting this to work.
I have a winform in C#. I am currently working with a listbox and a picturebox to display embedded image resources. I want to populate the listbox with just the file name, as the full path is longer than the width of the listbox can accommodate on my form.
Here is some code I was working with:
string[] x = System.IO.Directory.GetFiles(#"C:\Users\bassp\Dropbox\VS Projects\WindowsFormsApplication1\WindowsFormsApplication1\Resources\", "*.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
foreach (string f in x)
{
string entry1 = Path.GetFullPath(f);
string entry = Path.GetFileNameWithoutExtension(f);
listBox1.DisplayMember = entry;
listBox1.ValueMember = entry1;
listBox1.Items.Add(entry);
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.ImageLocation = listBox1.SelectedItem.ToString();
}
If I populate the listbox with the full path,(entry1), things work pretty smooth other than not being able to see the image name you will be selecting due to the length of the full path.
When I try to populate the listbox with (entry), just the file names appear in the listbox, which is desireable, however, the image will no longer open on selection from the listbox.
How can I get this working correctly? Help is greatly appreciated.
Patrick

You're on the right track by setting the DisplayMember and ValueMember properties, but you'd need to make a few corrections, and it might not be necessary here.
Store the original directory path in a separate variable, then just combine that with the file name in your SelectedIndexChanged event to get the original file path.
string basePath =
#"C:\Users\bassp\Dropbox\VS Projects\WindowsFormsApplication1\WindowsFormsApplication1\Resources\";
string[] x = Directory.GetFiles(basePath, "*.jpg");
foreach (string f in x)
{
listBox1.Items.Add(Path.GetFileNameWithoutExtension(f));
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.ImageLocation =
Path.Combine(basePath, listBox1.SelectedItem.ToString()) + ".jpg";
}

Grant answer is perfectly ok for a simple task like this, but i'll explain another way that may be useful in other situations.
You can define a class to store your filenames and paths, something like:
class images
{
public string filename { get; set; }
public string fullpath { get; set; }
}
This way, your code could be like:
string[] x = System.IO.Directory.GetFiles(#"C:\Users\bassp\Dropbox\VS Projects\WindowsFormsApplication1\WindowsFormsApplication1\Resources\", "*.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
List<images> imagelist=new List<images>();
foreach (string f in x)
{
images img= new images();
img.fullpath = Path.GetFullPath(f);
img.filename = Path.GetFileNameWithoutExtension(f);
imagelist.Add(img);
}
listBox1.DisplayMember = "filename";
listBox1.ValueMember = "fullpath";
listBox1.DataSource = imagelist;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.ImageLocation = ((images)listBox1.SelectedItem).fullpath;
}
I have not tested it,maybe it has any typo, but i hope you get the idea.

Related

Create a picturebox_clicked event for each picturebox created

private Form1 form1 { get; set; }
readonly HttpClient httpClient = new();
public static string FolderPath = #".\Storage";
public static int picNum = 0;
public static List<string> outofScopeURL = new List<string>();
private async void Detailed_View_Load_1(object sender, EventArgs e)
{
DirectoryInfo directory = new(FolderPath);
FileInfo[] files = directory.GetFiles();
string[] FileFormats = { ".png", ".jpg", ".jpeg", ".txt" };
for (int pictureCreator = 0; pictureCreator < files.Length; pictureCreator++)
{
FileInfo file = files[pictureCreator];
if (file.FullName.EndsWith(FileFormats[3]))
{
string url = File.ReadAllText(file.FullName);
if (url != null)
{
try
{
Image gif = Image.FromStream(await httpClient.GetStreamAsync(url));
PictureBox picture = new PictureBox
{
Name = url,
Size = new(38, 38),
Image = gif,
Location = new((gif.Width * pictureCreator), 0),
SizeMode = PictureBoxSizeMode.Zoom
};
this.Controls.Add(picture);
MessageBox.Show(picture.Name);
outofScopeURL.Add(url);
picture.Click += Picture_Click;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
picNum++;
}
}
}
What I'm trying to achieve:
I'm trying to look in a specific directory for text files, then I want to read the files and extract the URL present in them.
After I got all of the URLs of all the text files present in my folder, I added them into a list so I could use them with their respective picturebox
For example, when URL1 has picture1 and URL2 has picture2, I want to set the text of the clipboard to URL1 when picturebox1 that has picture1 applied to it is clicked.
What I have tried: I have tried making a new picturebox_Clicked event in the pictureCreator for loop but the problem is that the event is always applied to the last picturebox created.
Any help is much appreciated.
Your question is about creating a picturebox_clicked event for each picturebox created.
The code you posted seems to be doing that but as mentioned in the comments, casting the sender argument would be the key to making event useful. Consider a click handler implemented similar to this:
private void onAnyPictureBoxClick(object? sender, EventArgs e)
{
if(sender is PictureBox pictureBox)
{
var builder = new List<string>();
builder.Add($"Name: {pictureBox.Name}");
builder.Add($"Tag: {pictureBox.Tag}");
builder.Add($"Image Location: {pictureBox.ImageLocation}");
MessageBox.Show(string.Join(Environment.NewLine, builder));
}
}
Now give it a test (simulating the part where the URLs are already collected from the local store).
public partial class MainForm : Form
{
public MainForm() =>InitializeComponent();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
int id = 0;
// Here we have "already read" the URLs from the local store.
foreach (var url in new string[]
{
"https://i.stack.imgur.com/eSiWr.png",
"https://i.stack.imgur.com/o5dmA.png",
"https://i.stack.imgur.com/aqAuN.png",
})
{
var dynamicPB = new PictureBox
{
Width = flowLayoutPanel.Width - SystemInformation.VerticalScrollBarWidth,
Height = 200,
SizeMode = PictureBoxSizeMode.Zoom,
BackColor = Color.Azure,
// In this case, the url is already stored here...
ImageLocation = url,
// ...but here are a couple of other ID options.
Name = $"pictureBox{++id}",
Tag = $"Tag Identifier {id}",
Padding = new Padding(10),
};
dynamicPB.Click += onAnyPictureBoxClick;
flowLayoutPanel.Controls.Add(dynamicPB);
}
}
.
.
.
}

WPF C# Read a txt file in Textbox who is selected in combobox

Maybe this is an old question, but I canĀ“t find a solution fpr my project. Let me explain:
I have 3 Textboxes, who I can fill with values.
1 Button who save the values of the textboxes in a *.txt file. The Name of the file is the value of the first textboxes.
Then there is a ComboBox where I can select the txt files.
But I cant find the right code, when I selected a file, I want to see the 3 values(3 different lines) of the file into the Textboxes. Can someone help me, I will show you the Codes maybe its easier to understand.
the first code to save the values (tb1-3 = Textbox) in the txt file:
private void savebutton_click(object sender, RoutedEventArgs e)
{
string folder = #"C:\Users\...\...\...\Debug\";
string filename = tb1.Text + ", " + tb2.Text;
string writerfile = folder + filename;
using (StreamWriter writer = new StreamWriter(writerfile))
{
writer.WriteLine(this.tb1.Text);
writer.WriteLine(this.tb2.Text);
writer.WriteLine(this.tb3.Text);
}
}
The second code is to show the txt files in the combobox(combo1):
private void comboboxloaded(object sender, RoutedEventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\...\...\...\Debug");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
combo1.Items.Add(file);
}
}
And know... I need help...
private void comboboxvalueselect(object sender, SelectionChangedEventArgs e)
{
// Maybe?????
string fileName = combo1.SelectedItem.ToString();
string filePath = System.IO.Path.Combine(#"C:\Users\...\...\...\Debug" + fileName + "*.txt");
// and something with StreamReader??????
}
If I understand the question it could be as simple as using File.ReadAllLines
Opens a text file, reads all lines of the file into a string array,
and then closes the file.
private void comboboxvalueselect(object sender, SelectionChangedEventArgs e)
{
const string somePath = #"C:\Users\...\...\...\Debug";
var fileName = combo1.SelectedItem.ToString();
var filePath = Path.Combine(somePath , fileName);
// where you need those lines to go
someTextBox.Text = File.ReadAllLines(filePath);
}

Complete folder picture viewer in c#

I am a complete newbie when it comes to programing. I followed the tutorial here to create a picture box. http://msdn.microsoft.com/en-u s/library/dd492135.aspx
I work in c#. Now i am going through and making some changes. Is there anyway to make a code so that there can be a next and back button?
Any help would be appriciated.
Thanks,
Rehan
If I understand well you want to have two buttons (Next, Back)
I make a little project and I will be happy if it helped you.
If you want this, continue reading:
First we have to declare imageCount and a List<string>: Imagefiles
so we have this
List<string> Imagefiles = new List<string>();
int imageCount = 0;
imageCount helps to change images using buttons
Imagefiles contains all Image paths of our photos
Now to change photos we have to declare a path first which wil contains all photos.
I use FolderBrowserDialog
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
findImagesInDirectory(fbd.SelectedPath);
}
}
You will see that I use findImagesInDirectory and this method doesnt exist. We have to create it.
This method will help us to filter all the files from the path and get only the image files
private void findImagesInDirectory(string path)
{
string[] files = Directory.GetFiles(path);
foreach(string s in files)
{
if (s.EndsWith(".jpg") || s.EndsWith(".png")) //add more format files here
{
Imagefiles.Add(s);
}
}
try
{
pictureBox1.ImageLocation = Imagefiles.First();
}
catch { MessageBox.Show("No files found!"); }
}
I use try because if no image files, with the above extension, exists code will break.
Now we declare all Image files (if they exists)
Next Button
private void nextImageBtn_Click(object sender, EventArgs e)
{
if (imageCount + 1 == Imagefiles.Count)
{
MessageBox.Show("No Other Images!");
}
else
{
string nextImage = Imagefiles[imageCount + 1];
pictureBox1.ImageLocation = nextImage;
imageCount += 1;
}
}
Previous Button
private void prevImageBtn_Click(object sender, EventArgs e)
{
if(imageCount == 0)
{
MessageBox.Show("No Other Images!");
}
else
{
string prevImage = Imagefiles[imageCount -1];
pictureBox1.ImageLocation = prevImage;
imageCount -= 1;
}
}
I believe my code help. Hope no bugs!

C# How to select an object on a listbox from another listbox

Say I want listBox1 to contain a set of first names. And when someone clicks on one of those first names, it will display the last name in listBox2 and already selected.
I seem to not be able to have the second listbox have it already selected.
So if the first item in listBox1 is selected, the first item in listBox2 is selected. And so on.
How would such be possible?
Here is some code:
private void materialFlatButton3_Click_1(object sender, EventArgs e)
{
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.Multiselect = true;
OpenFileDialog1.Filter = "DLL Files|*.dll";
OpenFileDialog1.Title = "Select a Dll File";
if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// put the selected result in the global variable
fullFileName = new List<String>(OpenFileDialog1.FileNames);
foreach (string s in OpenFileDialog1.FileNames)
{
listBox2.Items.Add(Path.GetFileName(s));
listBox4.Items.Add(s);
}
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string text = listBox2.GetItemText(listBox2.SelectedItem);
textBox3.Text = text;
}
In listbox4, it displays the full path. In listbox2, it displays just the name of the file.
How would I make it so when someone clicks on a file in listbox2, its corresponding path will be selected in listbox4?
Create you own type for storing and displaying the file names:
public class FileItem
{
public FileItem (string path) => FullPath = path;
public string FullPath { get; }
public override ToString() => Path.GetFileName(FullPath);
}
And add these items to the listbox. That way you can store the full path and display the file name at the same time.
Alternatively just keep a reference to the original Files array or copy its content to another array. Then get the full path from this array through the selected index instead of from a second listbox ony used to store things.
Create a class which represent full path and name for displaying.
Then use bind loaded data to the ListBox
public class MyPath
{
public string FullPath { get; private set; }
public string Name '
{
get { return Path.GetFileName(s) }
}
public MyPath(string path)
{
FullPath = path;
}
}
// Load and bind it to the ListBox
var data = OpenFileDialog1.FileNames
.Select(path => new MyPath(path))
.ToList();
// Name of the property which will be used for displaying text
listBox1.DisplayMember = "Name";
listBox1.DataSource = data;
private void ListBox1_SelectedValueChanged(object sender, EventArgs e)
{
var selectedPath = (MyPath)ListBox1.SelectedItem;
// Both name and full path can be accesses without second listbox
// selectedPath.FullPath
// selectedPath.Name
}

Window Media PLayer in C#

i'm building a Music PLayer and so i choose to use the library of Window Media Player:
Now i got stuck 'cos i wish show the song's name in a listBox and change songs in real time but i don't know how go on.
I store songs from a Folder and so when the Music Player run the songs from the Url choose.
I show you a code snippet :
private void PlaylistMidday(String folder, string extendsion)
{
string myPlaylist = "D:\\Music\\The_Chemical_Brothers-Do_It_Again-(US_CDM)-2007-SAW\\";
ListView musicList = new ListView();
WMPLib.IWMPPlaylist pl;
WMPLib.IWMPPlaylistArray plItems;
plItems = player1.playlistCollection.getByName(myPlaylist);
if (plItems.count == 0)
pl = player1.playlistCollection.newPlaylist(myPlaylist);
else
pl = plItems.Item(0);
DirectoryInfo dir = new DirectoryInfo(folder);
FileInfo[] files = dir.GetFiles(extendsion, SearchOption.AllDirectories);
foreach (FileInfo file in files)
{
string musicFile01 = file.FullName;
string mName = file.Name;
ListViewItem item = new ListViewItem(mName);
musicList.Items.Add(item);
WMPLib.IWMPMedia m1 = player1.newMedia(musicFile01);
pl.appendItem(m1);
}
player1.currentPlaylist = pl;
player1.Ctlcontrols.play();
}
On Load i decide to play the songs of "myPLaylist" so i ask you do you know some way how to show the songs of my playlist in a listbox and when i click on the selected item i will change songs?
Thansk for your support.
Nice Regards
Instead of adding songs to playlist, you can add them to a List<string> as a return value. On load event, you just call the method that get list of media file paths in the folder, and then add them into a listbox.
To change the song being played, you just need to add SelectedValueChanged/SelectedItemChanged event, and in this event, get the file path that is currently selected in the listbox, then have WMP played it for you :)
private void Form1_Load(object sender, EventArgs e)
{
List<string> str = GetListOfFiles(#"D:\Music\Bee Gees - Their Greatest Hits - The Record");
listBox1.DataSource = str;
listBox1.DisplayMember = "str";
}
private List<string> GetListOfFiles(string Folder)
{
DirectoryInfo dir = new DirectoryInfo(Folder);
FileInfo[] files = dir.GetFiles("*.mp3", SearchOption.AllDirectories);
List<string> str = new List<string>();
foreach (FileInfo file in files)
{
str.Add(file.FullName);
}
return str;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string strSelected = listBox1.SelectedValue.ToString();
MessageBox.Show(strSelected); //Just demo, you can add code that have WMP played this file here
}
a quick solution. :). Not very good, but it works. Help this hope

Categories

Resources