c#.NET ListBox 具有动态数据和多选问题

发布于 2024-11-13 09:55:23 字数 7453 浏览 3 评论 0原文

我试图从其中包含多选和动态 ListItems 的 ListBox 获取值。我的问题是,一旦按下“分配”按钮,我就无法获取值。

我的想法是,我有大约 10-15 个列表项,应该为它们分配值。我希望能够选择其中 5 个,然后按分配按钮,然后继续为列表中剩余的这些项目分配其他值。

由于某种原因,我的 ListBox.Item.Count 总是返回 1 行。

问题:在 .NET 4.0 中使用 ListBox 时,是否有一些不明显的地方需要考虑?

部分代码

前面:

 <fieldset>
    <legend>
       <asp:Label ID="Label1" runat="server" 
            Text="<%$ Resources:lang, ExtensionsTitleAB %>"></asp:Label>
    </legend>
    <div class="extLeft"> 
       <table>
          <tr>
             <td>
                <asp:Label ID="Label5" runat="server" 
                     Text="<%$ Resources:lang, ExtensionsTmNumber %>"></asp:Label>
             </td>
             <td>
                <asp:TextBox runat="server" ID="txtTmNumber"></asp:TextBox>
             </td>
          </tr>
          <tr>
             <td>
                <asp:Label ID="Label6" runat="server"
                     Text="<%$ Resources:lang, ExtensionsTmName %>"></asp:Label>
             </td>
             <td>
                <asp:TextBox runat="server" ID="txtTmName"></asp:TextBox>
              </td>
           </tr>
           <tr>
              <td>
                 <asp:Label ID="Label7" runat="server"
                      Text="<%$ Resources:lang, ExtensionsTmRegistered %>">
                 </asp:Label>
              </td>
              <td>
                 <asp:TextBox runat="server" ID="txtTmRegistered"></asp:TextBox>
              </td>
           </tr>
           <tr>
              <td>
                 <asp:Label ID="Label8" runat="server" 
                      Text="<%$ Resources:lang, ExtensionsTmLocality %>">
                 </asp:Label>
              </td>
              <td>
                 <asp:TextBox runat="server" ID="txtTmLocality"></asp:TextBox>
              </td>
           </tr>
           <tr>
              <td>
                 <asp:Label ID="Label9" runat="server" 
                      Text="<%$ Resources:lang, ExtensionsMemberShipId %>">
                 </asp:Label>
              </td>
              <td>
                 <asp:TextBox runat="server" ID="txtMembershipIdFaseOne">
                 </asp:TextBox>
              </td>
           </tr>
        </table>
     </div>
     <div class="extMiddle">            
        <asp:Button runat="server" ID="btnAssignAB" OnClick="btnAssign_Click"
                    Text="<%$ Resources:lang, ButtonAssignExtensions %>" /> 
     </div>
     <div class="extRight">
        <p><asp:Label ID="Label4" runat="server" 
                Text="<%$ Resources:lang, ExtensionsListHelp %>">
           </asp:Label>
        </p>
        <asp:ListBox runat="server" ID="listABContainer" 
                     SelectionMode="Multiple" AutoPostBack="false">
        </asp:ListBox>
     </div>
  </fieldset>    

隐藏代码:

public partial class extensions : System.Web.UI.Page
    {
        private model.OrderHandling orderHandling;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["dataobject"] != null)
            {
                orderHandling = (OrderHandling)Session["dataobject"];
            }
            else
            {
                String url = "http://" + Request.Url.Authority + "/Default.aspx";
                Response.Redirect(url);
            }

            if (!IsPostBack)
            {
                addListItems();
            }                    
        }

        private void addListItems()
        {
            foreach (OrderLine line in orderHandling.order.getOrderLines())
            {
                if (line.price.getPriceType().Equals(Price_Types.SUNRISE_ONE) 
                  || line.price.getPriceType().Equals(Price_Types.SUNRISE_TWO))
                {
                    listABContainer.Items.Add(
                      new ListItem(line.domain.domainName, line.domain.domainName));

                    System.Diagnostics.Debug.WriteLine("added a domain " + 
                       "to list listABContainer : " + line.domain.domainName);
                }
                else if (line.price.getPriceType().Equals(Price_Types.LANDRUSH)
                        || line.price.getPriceType().Equals(Price_Types.GENERAL))
                {
                    listCDContainer.Items.Add(
                       new ListItem(line.domain.domainName, line.domain.domainName));

                    System.Diagnostics.Debug.WriteLine("added a domain " +
                       "to list listCDContainer : " + line.domain.domainName);
                }
            }            
        }

        protected void btnAssign_Click(object sender, EventArgs e)
        {                
                assignTMExtensions(); 
        }

        private bool assignTMExtensions()
        {
            bool success = true;

            TradeMarkExtension tmExt = new TradeMarkExtension();

            String errorMsg = "";

            if (!String.IsNullOrEmpty(txtTmNumber.Text) 
                  && 
               tmExt.isValid(EXTENSION_KEYS.TM_NUMBER, txtTmNumber.Text, null))
            {
                tmExt.setExtension(EXTENSION_KEYS.TM_NUMBER, txtTmNumber.Text);
            }               

            if (success)
            {
                System.Diagnostics.Debug.WriteLine("Succes: time for domainExtension, listCount : " + listABContainer.Items.Count);
                foreach (ListItem list in listABContainer.Items)
                {
                    if (list.Selected)
                    {
                        System.Diagnostics.Debug.WriteLine("Found a selected item " + list.Value);
                        try
                        {
                            OrderLine ol = orderHandling.order.getOrderLine(list.Value);
                            ol.domain.addExtension(tmExt);

                            System.Diagnostics.Debug.WriteLine("Addedd domainExtension");
                        }
                        catch (Exception e)
                        {
                            System.Diagnostics.Debug.WriteLine("FAILED domainExtension");
                            showError.Text = "An exception has occured. Please reload the page and try again.";
                            return false;
                        }
                    }
                }
                Session["dataobject"] = orderHandling;
                removeListItems(listABContainer);
            }
            else
            {
                showError.Text = errorMsg;
            }

            return success;
        }

        private void removeListItems(ListBox list)
        {
            int i = 0;
            while(i < list.Items.Count)
            {
                if (list.Items[i].Selected)
                {
                    list.Items.RemoveAt(i);
                }

                i++;
            }
        }
    }

Im trying to get values from a ListBox that has multiselection and dynamic ListItems in it. My problem is that I can't get the values once I press my "assign" button.

The idea is that I have like 10-15 listitems and they should be assigned with values. And I want to be able to select like 5 of them and press my assign button and then continue to assign other values to these items left in the list.

For som reason my ListBox.Item.Count always returns like 1 row.

Question: Is there something you need to think about when using ListBox in .NET 4.0 that isn't obvious?

Parts of the code

Front:

 <fieldset>
    <legend>
       <asp:Label ID="Label1" runat="server" 
            Text="<%$ Resources:lang, ExtensionsTitleAB %>"></asp:Label>
    </legend>
    <div class="extLeft"> 
       <table>
          <tr>
             <td>
                <asp:Label ID="Label5" runat="server" 
                     Text="<%$ Resources:lang, ExtensionsTmNumber %>"></asp:Label>
             </td>
             <td>
                <asp:TextBox runat="server" ID="txtTmNumber"></asp:TextBox>
             </td>
          </tr>
          <tr>
             <td>
                <asp:Label ID="Label6" runat="server"
                     Text="<%$ Resources:lang, ExtensionsTmName %>"></asp:Label>
             </td>
             <td>
                <asp:TextBox runat="server" ID="txtTmName"></asp:TextBox>
              </td>
           </tr>
           <tr>
              <td>
                 <asp:Label ID="Label7" runat="server"
                      Text="<%$ Resources:lang, ExtensionsTmRegistered %>">
                 </asp:Label>
              </td>
              <td>
                 <asp:TextBox runat="server" ID="txtTmRegistered"></asp:TextBox>
              </td>
           </tr>
           <tr>
              <td>
                 <asp:Label ID="Label8" runat="server" 
                      Text="<%$ Resources:lang, ExtensionsTmLocality %>">
                 </asp:Label>
              </td>
              <td>
                 <asp:TextBox runat="server" ID="txtTmLocality"></asp:TextBox>
              </td>
           </tr>
           <tr>
              <td>
                 <asp:Label ID="Label9" runat="server" 
                      Text="<%$ Resources:lang, ExtensionsMemberShipId %>">
                 </asp:Label>
              </td>
              <td>
                 <asp:TextBox runat="server" ID="txtMembershipIdFaseOne">
                 </asp:TextBox>
              </td>
           </tr>
        </table>
     </div>
     <div class="extMiddle">            
        <asp:Button runat="server" ID="btnAssignAB" OnClick="btnAssign_Click"
                    Text="<%$ Resources:lang, ButtonAssignExtensions %>" /> 
     </div>
     <div class="extRight">
        <p><asp:Label ID="Label4" runat="server" 
                Text="<%$ Resources:lang, ExtensionsListHelp %>">
           </asp:Label>
        </p>
        <asp:ListBox runat="server" ID="listABContainer" 
                     SelectionMode="Multiple" AutoPostBack="false">
        </asp:ListBox>
     </div>
  </fieldset>    

The codebehind:

public partial class extensions : System.Web.UI.Page
    {
        private model.OrderHandling orderHandling;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["dataobject"] != null)
            {
                orderHandling = (OrderHandling)Session["dataobject"];
            }
            else
            {
                String url = "http://" + Request.Url.Authority + "/Default.aspx";
                Response.Redirect(url);
            }

            if (!IsPostBack)
            {
                addListItems();
            }                    
        }

        private void addListItems()
        {
            foreach (OrderLine line in orderHandling.order.getOrderLines())
            {
                if (line.price.getPriceType().Equals(Price_Types.SUNRISE_ONE) 
                  || line.price.getPriceType().Equals(Price_Types.SUNRISE_TWO))
                {
                    listABContainer.Items.Add(
                      new ListItem(line.domain.domainName, line.domain.domainName));

                    System.Diagnostics.Debug.WriteLine("added a domain " + 
                       "to list listABContainer : " + line.domain.domainName);
                }
                else if (line.price.getPriceType().Equals(Price_Types.LANDRUSH)
                        || line.price.getPriceType().Equals(Price_Types.GENERAL))
                {
                    listCDContainer.Items.Add(
                       new ListItem(line.domain.domainName, line.domain.domainName));

                    System.Diagnostics.Debug.WriteLine("added a domain " +
                       "to list listCDContainer : " + line.domain.domainName);
                }
            }            
        }

        protected void btnAssign_Click(object sender, EventArgs e)
        {                
                assignTMExtensions(); 
        }

        private bool assignTMExtensions()
        {
            bool success = true;

            TradeMarkExtension tmExt = new TradeMarkExtension();

            String errorMsg = "";

            if (!String.IsNullOrEmpty(txtTmNumber.Text) 
                  && 
               tmExt.isValid(EXTENSION_KEYS.TM_NUMBER, txtTmNumber.Text, null))
            {
                tmExt.setExtension(EXTENSION_KEYS.TM_NUMBER, txtTmNumber.Text);
            }               

            if (success)
            {
                System.Diagnostics.Debug.WriteLine("Succes: time for domainExtension, listCount : " + listABContainer.Items.Count);
                foreach (ListItem list in listABContainer.Items)
                {
                    if (list.Selected)
                    {
                        System.Diagnostics.Debug.WriteLine("Found a selected item " + list.Value);
                        try
                        {
                            OrderLine ol = orderHandling.order.getOrderLine(list.Value);
                            ol.domain.addExtension(tmExt);

                            System.Diagnostics.Debug.WriteLine("Addedd domainExtension");
                        }
                        catch (Exception e)
                        {
                            System.Diagnostics.Debug.WriteLine("FAILED domainExtension");
                            showError.Text = "An exception has occured. Please reload the page and try again.";
                            return false;
                        }
                    }
                }
                Session["dataobject"] = orderHandling;
                removeListItems(listABContainer);
            }
            else
            {
                showError.Text = errorMsg;
            }

            return success;
        }

        private void removeListItems(ListBox list)
        {
            int i = 0;
            while(i < list.Items.Count)
            {
                if (list.Items[i].Selected)
                {
                    list.Items.RemoveAt(i);
                }

                i++;
            }
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧时浪漫 2024-11-20 09:55:23

像这样的东西吗?

ASPX页面

<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" AutoPostBack="false" />
<asp:Button ID="ButtonSubmit" runat="server" Text="Submit" OnClick="ButtonSubmit_Click" />

代码隐藏

   protected void Page_Load(object sender, EventArgs e)
   {
      if (!IsPostBack)
      {
         DataBindListBox();
      }
   }

   protected void ButtonSubmit_Click(object sender, EventArgs e)
   {
      List<ListItem> selectedItems1 = ListBox1.Items.Cast<ListItem>().Where(li => li.Selected).ToList();

      // or

      string[] selectedItems2 = (Request.Form[ListBox1.UniqueID] ?? string.Empty).Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
   }

   private void DataBindListBox()
   {
      var data = Enumerable.Range(1, 5).Select(i => new { Text = i.ToString(), Value = i.ToString() }).ToList();

      ListBox1.DataSource     = data;
      ListBox1.DataTextField  = "Text";
      ListBox1.DataValueField = "Value";
      ListBox1.DataBind();
   }

Something like this?

ASPX page

<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" AutoPostBack="false" />
<asp:Button ID="ButtonSubmit" runat="server" Text="Submit" OnClick="ButtonSubmit_Click" />

Code Behind

   protected void Page_Load(object sender, EventArgs e)
   {
      if (!IsPostBack)
      {
         DataBindListBox();
      }
   }

   protected void ButtonSubmit_Click(object sender, EventArgs e)
   {
      List<ListItem> selectedItems1 = ListBox1.Items.Cast<ListItem>().Where(li => li.Selected).ToList();

      // or

      string[] selectedItems2 = (Request.Form[ListBox1.UniqueID] ?? string.Empty).Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
   }

   private void DataBindListBox()
   {
      var data = Enumerable.Range(1, 5).Select(i => new { Text = i.ToString(), Value = i.ToString() }).ToList();

      ListBox1.DataSource     = data;
      ListBox1.DataTextField  = "Text";
      ListBox1.DataValueField = "Value";
      ListBox1.DataBind();
   }
玩套路吗 2024-11-20 09:55:23

一方面,这似乎是错误的:

private void removeListItems(ListBox 列表)
{
    整数 i = 0;
    while(i < list.Items.Count)
    {
        if (列表.Items[i].Selected)
        {
            列表.Items.RemoveAt(i);
        }

        我++;
    }
}

删除项目时不要增加 i ,否则会跳过项目。

当然,这只会隐藏下一个选定的项目......

for one thing this seems wrong:

private void removeListItems(ListBox list)
{
    int i = 0;
    while(i < list.Items.Count)
    {
        if (list.Items[i].Selected)
        {
            list.Items.RemoveAt(i);
        }

        i++;
    }
}

Don't increment i when you remove an item or you'll skip items.

Of course, that only hides the very next selected item...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文