[英]store selected value of multiple list box items in asp.net
I have a listbox control data bound to a data source and I want to be able to get the value of each selected item so that I can use that information to form an insert query for another table. 我有一个绑定到数据源的列表框控件数据,并且我希望能够获取每个选定项的值,以便可以使用该信息形成对另一个表的插入查询。 In other words be able to select a few items out of the returned list and get the selected value of each.
换句话说,能够从返回的列表中选择一些项目并获得每个项目的选定值。 I tried using a for each statement but came up with some strange numbers.
我尝试为每个语句使用a,但是想出了一些奇怪的数字。
Here's an example with a list box allowing multiple items to be selected and a button which retrieves the selected items: 这是一个示例,其中有一个列表框允许选择多个项目,还有一个用于检索所选项目的按钮:
<%@ 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>
I finally figured it out 我终于想通了
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.