列表框项未被移动到asp . net中的其他列表框
本文关键字:列表 net 其他 asp 移动 | 更新日期: 2023-09-27 18:09:56
我有两个列表框,一个是源列表框,一个是目标列表框。
我想在按钮单击事件后将所选项目转移到目标列表框。
我在互联网上搜索并从这里找到了样本。但在我的情况下,它不起作用。
我的ASP源文件是:
<asp:Table ID="tbvl" Width="100%" runat="server">
<asp:TableRow>
<asp:TableCell Width="45%">
<asp:ListBox ID="lstsource" CssClass="uppercase" runat="server" Width="100%" Height="140" SelectionMode="Multiple"></asp:ListBox>
</asp:TableCell>
<asp:TableCell Width="10%" HorizontalAlign="Center" Height="100%">
<asp:Table ID="Table1" runat="server" Height="100%">
<asp:TableRow>
<asp:TableCell Height="25%"><asp:Button ID="btnsd" CssClass="button" runat="server" Text=">>" Width="40" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell Height="25%"><asp:Button ID="btnds" runat="server" CssClass="button" Text="<<" Width="40" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell Height="25%"><asp:Button ID="btnallsd" runat="server" CssClass="button" Text=">" Width="40" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell Height="25%"><asp:Button ID="btnallds" runat="server" CssClass="button" Text="<" Width="40" /></asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:TableCell>
<asp:TableCell Width="50%">
<asp:ListBox ID="lstdestination" runat="server" CssClass="uppercase" Width="100%" Height="140" SelectionMode="Multiple"></asp:ListBox>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
我的Click()
事件是;
void btnallsd_Click(object sender, EventArgs e)
{
for (int i = lstsource.Items.Count - 1; i >= 0; i--)
{
if (lstsource.Items[i].Selected)
{
lstdestination.Items.Add(lstsource.Items[i]);
lstdestination.ClearSelection();
lstsource.Items.Remove(lstsource.Items[i]);
}
}
}
当我点击按钮页面只是得到刷新,但项目不添加到目标列表框。
我该怎么做才能得到正确的输出。
请帮。
您必须首先确保ListBoxes
在回发时没有绑定。否则,您将始终使用默认项填充它们,并且它们将再次被取消选中。
使用IsPostBack
属性,例如:
protected void Page_Load(Object sendeer, EventArgs e)
{
if(!IsPostBack)
{
DataBindListBoxes();
}
}
您还必须使按钮单击事件处理程序至少受到保护,并且将事件处理程序添加到aspx标记中(或以编程方式在代码后面):
后台代码:protected void btnallsd_Click(object sender, EventArgs e){//...}
aspx:
<asp:Button ID="btnallsd" OnClick="btnallsd_Click" ....
也可以使用Linq:
来查找选中的项目protected void btnallsd_Click(object sender, EventArgs e)
{
var selected = lstsource.Items.Cast<ListItem>()
.Where(li => li.Selected);
while (selected.Any())
{
var item = selected.First();
lstdestination.Items.Add(item);
lstsource.Items.Remove(item);
}
lstdestination.ClearSelection();
}
试试这个:
private void MoveListBoxItems(ListBox source, ListBox destination)
{
ListBox.SelectedObjectCollection sourceItems = source.SelectedItems;
foreach (var item in sourceItems)
{
destination.Items.Add(item);
}
while (source.SelectedItems.Count > 0)
{
source.Items.Remove(source.SelectedItems[0]);
}
}
使用:当你从1移动到2按钮时,点击事件:
MoveListBoxItems(listBox1, listBox2);
Try This
protected void moveRight_Click(object sender, EventArgs e)
{
for (int i = 0; i < lbFirst.Items.Count; i++)
{
if (lbFirst.Items[i].Selected)
{
lbSecond.Items.Add(lbFirst.Items[i]);
lbFirst.Items.Remove(lbFirst.Items[i]);
}
}
}