【问题标题】:C# WindowsForm Combobox showing wrong "Display Value"C# Windows 窗体组合框显示错误的“显示值”
【发布时间】: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,旁边没有目录。

问题:

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

【问题讨论】:

标签: c#


【解决方案1】:

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

原因是:

代替:

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的评论指导

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

【讨论】:

    猜你喜欢
    • 2019-06-28
    • 1970-01-01
    • 2020-05-25
    • 2022-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    相关资源
    最近更新 更多