溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何對(duì)ListBox實(shí)現(xiàn)添加移除操作

發(fā)布時(shí)間:2021-10-14 14:04:08 來(lái)源:億速云 閱讀:110 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)如何對(duì)ListBox實(shí)現(xiàn)添加移除操作,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

前臺(tái)代碼:

代碼如下:


<div>
<asp:ListBox ID="ListBox1" runat="server" Height="123px" Width="113px" SelectionMode="Multiple">
<asp:ListItem>tom</asp:ListItem>
<asp:ListItem>jion</asp:ListItem>
<asp:ListItem>j</asp:ListItem>
<asp:ListItem>l</asp:ListItem>
<asp:ListItem>k</asp:ListItem>
</asp:ListBox>
&nbsp;<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="添加" />
&nbsp;
<asp:Button ID="btnRemove" runat="server" Text="移除" OnClick="btnRemove_Click" />
&nbsp;<asp:ListBox ID="ListBox2" runat="server" Height="123px" SelectionMode="Multiple" Width="113px"></asp:ListBox>
</div>


后臺(tái)代碼:

代碼如下:


protected void btnAdd_Click(object sender, EventArgs e)
{
#region listbox添加記錄的一種錯(cuò)誤理解
//選擇多條記錄的時(shí)候,會(huì)有一條沒(méi)有被添加,這是因?yàn)楫?dāng)一條記錄被移除后,原來(lái)的第二條記錄的index為0
//for (int i = 0; i < ListBox1.Items.Count; i++)
//{
// if (ListBox1.Items[i].Selected == true)
// {
// ListBox2.Items.Add(ListBox1.SelectedValue);
// ListBox1.Items.Remove(ListBox1.SelectedValue);
// }
//}
#endregion
#region listbox利用index索引號(hào)進(jìn)行添加的簡(jiǎn)單寫(xiě)法
//while (0 <= ListBox1.SelectedIndex)
//{
// ListBox2.Items.Add(ListBox1.SelectedItem);
// ListBox1.Items.Remove(ListBox1.SelectedItem);
//}
#endregion
#region listbox的另一種成功添加方法
List<ListItem> list = new List<ListItem>();
for (int i = ListBox1.Items.Count - 1; i >= 0; i--)
{
if (ListBox1.Items[i].Selected == true)
{
list.Add(ListBox1.Items[i]);
ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
for (int i = 0; i <=list.Count - 1; i++)
{
ListBox2.Items.Add(list[i]);
}
#endregion
}
protected void btnRemove_Click(object sender, EventArgs e)
{
while (0 <= ListBox2.SelectedIndex)
{
ListBox1.Items.Add(ListBox2.SelectedItem);
ListBox2.Items.Remove(ListBox2.SelectedItem);
}
}

關(guān)于“如何對(duì)ListBox實(shí)現(xiàn)添加移除操作”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI