ListBox控制元件的操作
阿新 • • 發佈:2020-08-11
Items的相關使用方法: 1、往listBox中新增一個數據 listBox.Items.Add("資料1"); 2、往listBox中新增多個數據集合 : string [] list = new string []{"admin","abcdefg","sqlserver"}; listBox.Items.AddRange(list); 3、在listBox指定位置插入一個新值 listBox.Items.Insert(3,"New Add"); 4、獲取listBox中的索引 int index = listBox.Items.IndexOf("admin");//獲取在listBox的索引 5、判斷是否存在 bool bi = listBox.items.Contains("sqlserver"); 6、清除指定的資料 listBox.Items.Remove("admin"); 7、清除指定索引位置的資料 listBox.Items.RemoveAt("admin");
當在listbox中要載入大量的資料時,最好使用以下兩個方法: 1、使用BeginUpdate可以防止控制元件閃爍 listBox1.BeginUpdate();//開頭加一個 中間的資料使用 “for迴圈”或“foreach迴圈” { List<UserInfo> list = new List<UserInfo>(); list.Add(new UserInfo() { ID = 1, Name = "張三" }); list.Add(new UserInfo() { ID = 2, Name = "李四" }); list.Add(new UserInfo() { ID = 3, Name = "王五" }); list.Add(new UserInfo() { ID = 4, Name = "趙六" }); //繫結資料 想的實際值一般來說 就會指定對應顯示值的編號 listBox1.DataSource = list;//選項的來源 listBox1.DisplayMember = "Name";//想顯示的文字對應屬性名 listBox1.ValueMember = "ID";//想的實際值 } 2、 listBox1.EndUpdate();//結尾加一個 注:往listbox中繫結資料載入 一定要使用 (DataSource、DisplayMember、ValueMember)三個屬性,否則資料顯示不出來