1. 程式人生 > >listbox控制元件用法詳解

listbox控制元件用法詳解

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();