代码之家  ›  专栏  ›  技术社区  ›  The Muffin Man

在asp.net中存储多个列表框项的选定值

  •  0
  • The Muffin Man  · 技术社区  · 14 年前

    我有一个绑定到数据源的listbox控件数据,我希望能够获取每个选定项的值,以便可以使用该信息为另一个表形成一个insert查询。换句话说,可以从返回的列表中选择一些项并获取每个项的选定值。我试着每句话都用一个,但得出了一些奇怪的数字。

    2 回复  |  直到 14 年前
        1
  •  2
  •   Darin Dimitrov    14 年前

    下面是一个示例,其中包含允许选择多个项的列表框和检索所选项的按钮:

    <%@ Page Title="Home Page" Language="C#" %>
    <script type="text/C#" runat="server">
        protected void Page_Load(object sender, EventArgs e) 
        {
            if (!IsPostBack)
            {
                list.DataSource = Enumerable.Range(1, 5).Select(x => new { Id = x, Text = "item " + x });
                list.DataValueField = "Id";
                list.DataTextField = "Text";
                list.DataBind();
            }
        }
    
        protected void BtnOK_Click(object sender, EventArgs e)
        {
            ListItem[] selectedItems = list.Items
                .Cast<ListItem>()
                .Where(item => item.Selected)
                .ToArray();
            // TODO: use the selected items here
        }
    </script>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head id="Head1" runat="server">
        <title></title>
    </head>
    <body>
        <form id="Form1" runat="server">
            <asp:ListBox ID="list" runat="server" SelectionMode="Multiple" />
            <asp:LinkButton ID="BtnOK" runat="server" OnClick="BtnOK_Click" Text="OK" />
        </form>
    </body>
    </html>
    
        2
  •  1
  •   The Muffin Man    14 年前

    我终于明白了

    protected void Button1_Click(object sender, EventArgs e)
    {
        string msg = "";
    
        foreach (ListItem li in ListBox_SubModel.Items)
        {
            if (li.Selected == true)
            {
                msg += "<br />" + li.Value + " is selected";
            }
        }
        Label_SubModel.Text = msg;
    }