【问题标题】:Get changes to multiselect listbox selected items获取对多选列表框所选项目的更改
【发布时间】:2011-11-09 22:34:40
【问题描述】:

如果不是回发和从数据库中选择的项目(如果适用),我有一个列表框数据绑定。如果我在列表框中选择新项目并回发,我的 foreach 逻辑总是只看到原始选择,而不是更改。一直在敲我的头在谷歌上寻找答案。下面是代码:

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

编辑:我应该添加列表框包含在更新面板中

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    希望这些能给你带来灵感。

    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)
        {
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      标记:

      <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>
      

      代码隐藏:

      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) {
                  }
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-10
        相关资源
        最近更新 更多