ListBox控制項準系統
來源:互聯網
上載者:User
ListBox準系統首先是清單項目的添加,用戶端實現代碼添加在listbox執行個體化代碼中間,例如:
<asp:ListItem Value="value" Selected=True>Text</asp:ListItem>
若在伺服器端實現,為避免每次載入時執行添加清單項目,上述程式碼封裝含在下面代碼中:
if(!IsPostBack)
{
}
WebForm頁面上須添加2個listbox(listbox1和lixtbox2)和2個命令按鈕,listbox1不為空白。清單項目從listbox1添加到listbox2須在Button1單擊事件中調用Add方法:
ListBox2.Items.Add(ListBox1.SelectedValue);
若要從listbox2中刪除清單項目的話須在Button2單擊事件中調用Remove方法:
ListBox2.Items.Remove(ListBox2.SelectedValue);
清單項目從listbox1添加到listbox2後,清單項目從listbox1中刪除:
int i=0;
while(i<ListBox1.Items.Count)
{
if(ListBox1.Items[i].Selected==true)
{
ListBox2.Items.Add(ListBox1.Items[i]);
ListBox1.Items.Remove(ListBox1.Items[i]);
}
else
i+=1;
}
這樣只能實現單項添加,想要實現多項添加,首先設定ListBox1的SelectionMode屬性值Multiple,ListBox1允許多項選中。
在Button1單擊事件中添加
foreach(ListItem MyItem in ListBox1.Items)
if(MyItem.Selected==true)
ListBox2.Items.Add(MyItem);
想要一次清空ListBox2中所有選項可在Button2單擊事件中調用clear方法,
ListBox2.Items.Clear();
若清單項目已經添加,不允許二次添加,Button1單擊事件中的程式碼封裝含在:
if(ListBox2.Items.FindByValue(ListBox1.SelectedValue)==null)
{
}
ListBox與資料庫綁定就是指定他的DataSource和DataTextField屬性,
ListBox2.DataSource=資料來源;
ListBox2.DataTextField="欄位名";
ListBox2.DataBind();