简体   繁体   English

C# WindowsForm Combobox 显示错误的“显示值”

[英]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:原因是:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM