Goal:
Get all file directories from MySQL and place them into a dictionary.
Display them into a combobox just as the filename. eg filename
Assign the combobox value as the the full directory. eg c:\users\user\desktop\filename.jpg
Code:
string filenames = "select filename from request_label_signoff where progress_user1 is null or progress_user2 is null";
//On load - load specific images from query above
private void Form15_Load(object sender, EventArgs e)
{
//Dict to store file into
Dictionary<string, string> files = new Dictionary<string, string>();
using (var conn = new MySqlConnection(connString))
{
conn.Open();
using (var cmd = new MySqlCommand(filenames, conn))
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//add filename without extension and full directory
files.Add(Path.GetFileNameWithoutExtension(reader.GetString(0)), reader.GetString(0));
}
}
}
}
comboBox1.DataSource = new BindingSource(files, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
value = ((KeyValuePair<string, string>)comboBox1.SelectedItem).Value;
pictureBox1.Image = Image.FromFile(value);
}
Problem:
For some reason the display value for the combobox shows like this:
Text output: [abc 123, C:\Users...]
Whereas it should be abc 123
without the directory next to it.
Question:
Why does he combo-box display value show both items?
You need to change the order of assignment in the combobox.
The reasons are:
- sometimes the displaymember assignment wont work. From StackOverflow Answer comment .
- Sometimes, selectedIndex event might fire if you set datasource first. Reference Stackoverflow Answer
Instead of:
comboBox1.DataSource = new BindingSource(files, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
it should be:
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
comboBox1.DataSource = new BindingSource(files, null);
Instead of using this: Dictionary<string, string> files = new Dictionary<string, string>();
I have used: var choices = new Dictionary<string, string>();
As guided in the comment by hans-passant
And everything works. Not sure what the difference was.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.