2017-03-06 13 views
0

所以我在學校做了一個關於音樂學校的課程,我想要做的一件事就是能夠從3個輸入值創建一個學費代碼(由6個字符組成)。 所以cbInstrument是一個組合框,cbLevel也是一個組合框,而rb10Lessons/rb20Lesoons是單選按鈕。當代碼運行時,我希望能夠根據這些值創建一個tuitionCode,因爲我選擇這些值時,學費代碼將顯示在與我選擇信息相同的表單中。如何使用c#visual studio中的子字符串從組合框創建代碼?

例如;如果在樂器的表格中點擊「Cello」,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; 
    } 
+0

你嘗試連接這些'codePart'變量嗎?另請注意:你的''「''子字符串不好。 – crashmstr

回答

3

您使用了錯誤的功能... Subtring將在字符串中返回一個字符串:例如:「123456」 .Substring(2,1) 「將返回 」3「

你需要的是簡單地收集您的字符串:

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

就是這樣

1

Substring的返回值是它自己的字符串,而不是對傳遞給它的字符串部分的引用。

C#6有一個功能叫做串插,看起來像這樣:

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

你也可以使用String.Format(...)如果你的VS版本不支持C#6的特性。

+0

不錯的功能!它支持智能和重構嗎? – Seb

+1

是的,你甚至可以將它與'@'結合起來用於預格式化的字符串。 – WereGoingOcean

相關問題