【问题标题】:How can I show only a part of a string in a combobox如何在组合框中仅显示字符串的一部分
【发布时间】:2019-03-25 09:46:52
【问题描述】:

在名称以相同方式开头的组合框中加载文件时出现问题?我只想显示由_分隔的字符串的第一个字母

Screenshot

private void frm_main_Load(object sender, EventArgs e)
    {
        string path = @"C:\Meteo";

        if (Directory.Exists(path))
        {
            listBox1.Items.Clear();
            string[] files = Directory.GetFiles(path);

            string[] dirs = Directory.GetDirectories(path);

            foreach (string file in files)
            {       
                listBox1.Items.Add(Path.GetFileName(file));
                comboBox2.Items.Add(Path.GetFileName(file));
            }

            foreach (string dir in dirs)
            {
                listBox1.Items.Add(Path.GetFileName(path));
            }      
        }

        else

        {
            MessageBox.Show("Директорията Meteo не е октирта в системен диск 'C:\'");
            Application.ExitThread();
        }      
    }

【问题讨论】:

标签: c# winforms combobox


【解决方案1】:

如果你想要第一个字母"0_2019_01_23.dat" => "0" 你可以写:

var formattedName = Path.GetFileName(file).Split('_').First();

如果你想截断"0_2019_01_23.dat" => "23.dat" 你可以写:

var formattedName = Path.GetFileName(file).Split('_').Last();

如果你想采取不同的部分"0_2019_01_23.dat" => "2019_01" 你可以写:

var formattedName = string.Join("_", Path.GetFileName(file).Split('_').Skip(1).Take(2));

要更改顺序"0_2019_01_23.dat" => "23_2019" 你可以写:

var parts = Path.GetFileNameWithoutExtension(file).Split('_');
var formattedName = string.Join("_", new []{parts[3], parts[1]});

【讨论】:

    猜你喜欢
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2015-07-08
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多