【问题标题】:How to create a code from comboboxes using substring in c# visual studio?如何在 C# Visual Studio 中使用子字符串从组合框创建代码?
【发布时间】:2017-03-06 19:23:04
【问题描述】:

所以我正在学校做关于音乐学校的课程,我想做的一件事是能够从 3 个输入的值创建一个学费代码(由 6 个字符组成)。 所以 cbInstrument 是一个组合框,cbLevel 也是一个组合框,而 rb10Lessons/rb20Lesoons 是单选按钮。当代码运行时,我希望能够在我选择这些值时从这些值创建一个学费代码,以便学费代码将显示在与我选择信息相同形式的标签中。

例如;如果在仪器的运行表格中单击“大提琴”,则 TuitionCode 显示为 CEL。之后,如果我点击 Level 为“Grade 1”,TuitionCode 就会显示为 CELB。然后如果我选择 10 节课,那么 TuitionCode = CELB10。

下面是代码示例:

private void Tuition_Click(object sender, EventArgs e)
    {
        string code = "";
        string codePart1 = code.Substring(0, 3);
        string codePart2 = code.Substring(3, 1);
        string codePart3 = code.Substring(4, 2);

        if (cbInstrument.Text == "Cello")
        {
            codePart1 = "CEL";
        }
        else if (cbInstrument.Text == "Clarinet")
        {
            codePart1 = "CLA";
        }
        else if (cbInstrument.Text == "Double Bass")
        {
            codePart1 = "DBA";
        }


        if ((cbLevel.Text == "None") || (cbLevel.Text == "Grade 1") || (cbLevel.Text == "Grade 2"))
        {
            codePart2 = "B";
        }
        else if ((cbLevel.Text == "Grade 3") || (cbLevel.Text == "Grade 4") || (cbLevel.Text == "Grade 5"))
        {
            codePart2 = "I";
        }

        if (rb10Lessons.Checked)
        {
            codePart3 = "10";
        }
        else if (rb20Lessons.Checked)
        {
            codePart3 = "20";
        }

        lblTuitionCode.Text = code;
    }

【问题讨论】:

  • 您是否尝试连接那些codePart 变量?另请注意:"" 上的子字符串不好。

标签: c# visual-studio substring


【解决方案1】:

您使用了错误的函数...Subtring 将返回字符串中的子字符串:例如:“123456”.Substring(2,1)" 将返回“3”

你需要的只是聚合你的字符串:

code = string.Format("{0}{1}{2}", codePart1, codePart2, codePart3);

就是这样

【讨论】:

    【解决方案2】:

    Substring 的返回值是它自己的字符串,而不是对传递给它的部分字符串的引用。

    C# 6 有一个称为字符串插值的功能,如下所示:

    code = $"{codePart1}{codePart2}{codePart3}";

    如果您的 VS 版本不支持 C# 6 功能,您也可以使用 String.Format(...)。

    【讨论】:

    • 不错的功能!是否支持智能和重构?
    • 是的,您甚至可以将其与 @ 结合使用以获取预格式化字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多