C# Windows 窗体组合框显示错误的“显示值”

Posted

技术标签:

【中文标题】C# Windows 窗体组合框显示错误的“显示值”【英文标题】:C# WindowsForm Combobox showing wrong "Display Value" 【发布时间】:2020-07-15 10:01:54 【问题描述】:

目标:

mysql 中获取所有文件目录并将它们放入字典中。

将它们作为文件名显示在组合框中。例如filename

将组合框值指定为完整目录。例如c:\users\user\desktop\filename.jpg

代码:

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);


问题:

由于某种原因,组合框的显示值如下所示:

文本输出:[abc 123, C:\Users...]

而它应该是abc 123,旁边没有目录。

问题:

为什么他的组合框显示值同时显示两个项目?

【问题讨论】:

您似乎以错误的方式填充组合框。谷歌了解如何填充组合框或使用此 SO 问题作为参考:***.com/questions/7423911/… Other way around. 【参考方案1】:

您需要更改组合框中的赋值顺序。

原因是:

有时显示成员分配不起作用。 From *** Answer comment。 有时,如果您先设置数据源,则可能会触发 selectedIndex 事件。 Reference *** Answer

代替:

comboBox1.DataSource = new BindingSource(files, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";

应该是:

comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
comboBox1.DataSource = new BindingSource(files, null);

【讨论】:

嗯...我试过了。它对我来说很好。调试它,看看哪个被加载到文件字典中 如果我将DisplayMember 设置为值。它只显示目录。但关键是在这些括号中显示两个值[]【参考方案2】:

而不是使用这个:Dictionary&lt;string, string&gt; files = new Dictionary&lt;string, string&gt;();

我用过:var choices = new Dictionary&lt;string, string&gt;();

按照hans-passant的评论指导

一切正常。不知道有什么区别。

【讨论】:

以上是关于C# Windows 窗体组合框显示错误的“显示值”的主要内容,如果未能解决你的问题,请参考以下文章

在 Windows 窗体应用程序 C# 中以编辑模式将值绑定到组合框

Windows 窗体中的刷新组合框

C# CaliburnMicro:如何根据在数据网格中选择的项目自动在组合框中显示值?

Windows 窗体中的多级组合框

第一章 C#入门 (Windows窗体应用程序)

在 c# 中使用文本框中的数据库值打开特定的 Windows 窗体