简体   繁体   中英

Get changes to multiselect listbox selected items

I have a listbox databound if not postback and items selected from a database (if applicable). If i select new items in the listbox and postback, my foreach logic always sees only the original selection, not the changes. Been banging my head trolling google for the answer. Here's the code behind:

  foreach (ListItem li in lsb.Items)
  {
    if (li.Selected)
    {
      try
      {
        [sql insert]
      }
    }
  }

EDIT: I should add the listbox is contained within and updatepanel

Hope these will give you muse.

protected void MyListBox_TextChanged(object sender, System.EventArgs e)
{
    try
    {
        listObject = sender as ListBox;

        if (listObjct ! = null && !CheckItemInDBorNot(listObject.Text))
        {
            // This item not exists in Db,
            // excute sql insert it into Db.
            Add(listOjbect.Text);
        }

    }
    catch (Exception ex)
    {

    }
}

markup:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
            <asp:ListItem Value="1" />
            <asp:ListItem Value="2" />
            <asp:ListItem Value="3" />
            <asp:ListItem Value="4" />
            <asp:ListItem Value="5" />
        </asp:ListBox>
        <asp:Button ID="btnPostback" runat="server" Text="Postback" OnClick="btnPostback_Click"/>
    </ContentTemplate>
</asp:UpdatePanel>

code-behind:

protected void btnPostback_Click(object sender, System.EventArgs e)
{
    for (int i = 0; i <= ListBox1.Items.Count - 1; i++) {
        ListItem li = ListBox1.Items(i);
        if (li.Selected) {
            try {
                string sValue = li.Text;
            // Do insert here

            } catch (Exception ex) {
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM