[英]C# WindowsForm Combobox showing wrong “Display Value”
Goal:目标:
Get all file directories from MySQL and place them into a dictionary.从 MySQL 获取所有文件目录并将它们放入字典中。
Display them into a combobox just as the filename.将它们显示到 combobox 中,就像文件名一样。 eg filename
例如filename
Assign the combobox value as the the full directory.将 combobox 值分配为完整目录。 eg c:\users\user\desktop\filename.jpg
例如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:出于某种原因,combobox 的显示值如下所示:
Text output: [abc 123, C:\Users...]
文本 output: [abc 123, C:\Users...]
Whereas it should be abc 123
without the directory next to it.而它应该是abc 123
旁边没有目录。
Question:问题:
Why does he combo-box display value show both items?为什么他的组合框显示值同时显示这两个项目?
You need to change the order of assignment in the combobox.您需要更改 combobox 中的分配顺序。
The reasons are:原因是:
- sometimes the displaymember assignment wont work.有时显示成员分配不起作用。 From StackOverflow Answer comment . 来自 StackOverflow 答案评论。
- Sometimes, selectedIndex event might fire if you set datasource first.有时,如果您先设置数据源,则可能会触发 selectedIndex 事件。 Reference Stackoverflow Answer 参考 Stackoverflow 答案
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>();
而不是使用这个: Dictionary<string, string> files = new Dictionary<string, string>();
I have used: var choices = new Dictionary<string, string>();
我用过: var choices = new Dictionary<string, string>();
As guided in the comment by hans-passant正如hans-passant的评论所指导的那样
And everything works.一切正常。 Not sure what the difference was.不知道有什么区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.