我希望用戶能夠在文本框中寫一些東西,并將該寫的值添加到串列框中。
但這是問題所在:
允許用戶在文本框內寫任何他想要的東西。但是當用戶想要將自己剛剛寫入的值添加到串列框時,只能將這些詞添加到串列框:
- 老虎
- 獅子
- 羊
- 鼠
- 老鼠
- 火烈鳥
- 狼
可以通過按下按鈕將寫入文本框內的值添加到串列框中。
提前致謝!
uj5u.com熱心網友回復:
您可以將單詞存盤在某個集合中,說 inHashSet<string>然后單擊按鈕檢查用戶輸入的單詞是否在集合中。
在WinForms的情況下,您可以這樣寫:
// Words we allow to add
private static HashSet<string> s_Words =
new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
"Tiger", "Lion", "Sheep", "Rat", "Mouse", "Flamingo", "Wolf",
};
// On button click we can add the word from myTextBox into myListBox
private void myButton_Click(object sender, EventArgs e) {
// Let us be nice and tolerate leading and trailing whitespaces
string text = myTextBox.Text.Trim();
// If word is in the collection ...
if (s_Words.ContainsKey(text))
myListBox.Items.Add(text); // ... we add it into to the listbox
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462698.html
標籤:C#
