ListBox控件可以一次呈現多個項,並且語序對控件中的選項進行選擇操作,ListBox類公開Items屬性,它是一個集合,類型為ListBox.ObjectCollection,是ListBox的一個嵌套類,該類實現了IList接口,可以調用Add方法向列表中添加新的項。ObjectCollection類提供了一個AddRange方法,允許一次性添加多個項。
通過設置ListBox控件的SelectionMode屬性可以控制ListBox的選擇行為,它是一個枚舉值
枚舉值 說明
None 如果設置該值,則無法選擇項
One 每次只能選擇一項
MultiSimple 可以選擇多項,第一次單擊某項時將其選中,再次單擊就可以取消選擇
MultiExtended 多選,可以使用(Ctrl)和(Shift)等控制鍵來輔助操作
1、繪制如下窗口(白色框使用ListBox控件)
2、在ListBox添加文字
4、添加RadioButton控件(Text屬性一定要一樣,要不然沒有辦法通過RadioButton按鈕的Text中獲取對應的值)
5、給RadioButton添加點擊共享事件
6、編輯代碼
private void OnRaidoButtonCheckChange(object sender, EventArgs e) { if (this.listBox1 == null) return; RadioButton rdbutton = sender as RadioButton; if (rdbutton.Checked) { string txt = rdbutton.Text;//獲取RadioButton text字符 //在枚舉數據類型中,調用Enum.Parse方法可以根據提供的枚舉值的名字轉換為枚舉值 //並將轉換的枚舉值賦值給ListBox1.SelectionMode listBox1.SelectionMode = (SelectionMode)Enum.Parse(typeof(SelectionMode), txt); } }
LIstBox控件有個Items屬性,可以通過自己編寫代碼向ListBox中添加列表選項。
private void btnAddItem_Click(object sender, EventArgs e) { //判斷TextBox中的文本是否為空 if (string.IsNullOrWhiteSpace(txtInput.Text)) { return; } //添加文本之前先判斷是否重復 // 摘要: // 找到的第一項 System.Windows.Forms.ListBox 以指定字符串開頭。 // // 參數: // s: // 要搜索的文本。 // // 返回結果: // 找到的第一項的從零開始的索引返回 ListBox.NoMatches 如果不找到任何匹配項。 // // 異常: // T:System.ArgumentOutOfRangeException: // 值 s 參數小於-1 或大於或等於項的計數。 if (listBox1.FindString(txtInput.Text) != ListBox.NoMatches) { MessageBox.Show("此項已經存在"); return; } //將文本框中文本加入到ListBox的列表項中 listBox1.Items.Add(txtInput.Text); //清空txtInput中的文本 txtInput.Clear(); } }