从列表框中检索每个项目并将其存储为字符串

时间:2014-01-28 09:26:48

标签: c# asp.net listbox

在aspx.cs中

 string CatID = string.Empty;
    foreach (ListItem li in ListBox1.Items)
    {
        if (li.Selected == true)
        {
            // get the value of the item in your loop
            CatID += li.Value + ",";
        }
    }

在aspx中

 <asp:ListBox ID="ListBox1" runat="server" DataSourceID="SqlDataSource1" SelectionMode="Multiple" 
    DataTextField="Username" DataValueField="Username" Height="175px" 
    Width="167px"></asp:ListBox>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:ProjectConnectionString %>" 
    SelectCommand="SELECT * FROM [login_det] WHERE ([Type] = @Type)">
    <SelectParameters>
        <asp:Parameter DefaultValue="User" Name="Type" Type="String" />
    </SelectParameters>
</asp:SqlDataSource>

上面显示了一段代码,当我在列表框中选择四个项目时,它将输出为abc,bcd,efg,hig,。现在是否有可能单独检索这些值并将其存储为字符串?.Like`

string a = “abc”;
String b=”bcd”;
String c=”efg”;` etc.

另一个冲突是列表框中可能有 100个项目。如果我选​​择了90个项目,我应该声明或用字符串变量分配每个项目,这是没有意义的。但是还有其他可能从列表框中存储或检索单个项目吗?

5 个答案:

答案 0 :(得分:1)

使用List<string>

List<string> result = new List<string>();
foreach (ListItem li in ListBox1.Items)
{
    if (li.Selected)
    {
        // get the value of the item in your loop
        result.Add(li.Value);
    }
}

答案 1 :(得分:1)

根据您的评论,您需要选择项目列表以进行进一步处理。你没有显示你的实际代码所以我将使用一个虚构的例子:

// Let me suppose you're using EF to store some data
using (var context = new DatabaseContext())
{
    foreach (var li in ListBox1.Items.Cast<ListItem>().Where(x => x.Selected))
    {
        // I assume you have user ID (as it's name) in the Value property
        // of each ListItem in your ListBox
        string userName = li.Value;

        var user = context.Users.FirstOrDefault(x => x.Name == userName);

        // This is not redundant, user may even be deleted in another session
        if (user != null)
        {
            // Do changes you need
            user.HasBeenSelected = true;
        }
    }

    // We're done, apply changes you made
    context.SaveChanges();
}

如您所见,您不需要为每个所选项目创建单独的变量,您可以列出它们,然后您不需要创建另一个临时列表,只需使用选择的项目来处理您必须这样做。

对不起,如果没有一些代码可以检查我就不能更具体,只是另一个让意图明确的例子:

foreach (var li in ListBox1.Items.Cast<ListItem>().Where(x => x.Selected))
{
    var user = Membership.GetUser(li.Value);
    if (user != null)
    {
        user.IsLockedOut = false;
        Membership.UpdateUser(user);
    }
}

从您的示例(仅用于说明目的!):

using (var connection = new SqlConnection(ProjectConnectionString))
{
    connection.Open();

    foreach (var li in ListBox1.Items.Cast<ListItem>().Where(x => x.Selected))
    {
        using (var command = connection.CreateCommand())
        {
            command.CommantText =
                "UPDATE [Login_det] SET Enabled = 0 WHERE Name = @UserName";

            command.Parameters.AddWithValue("UserName", li.Value);
            command.ExecuteNonQuery();
        }
    }
}

请注意,如果您有可能不需要执行多个命令的项目列表,则可以使用带有表格参数的单个命令。请参阅此处的this post以获取一个好例子。

答案 2 :(得分:0)

string CatID = string.Empty;
int i = ListBox1.Items.Count(); //not sure with this
string[] CatValues = new string[i];
int iCount = 0;
foreach (ListItem li in ListBox1.Items)
{
    if (li.Selected == true)
    {
        // get the value of the item in your loop
        CatID += li.Value + ",";
        CatValues[iCount] = li.Value;
        iCount++;
    }
}

然后您可以循环CatValues以获取所有值。我不知道这是否会对你有所帮助

答案 3 :(得分:0)

您可以使用Linq提取所有选定的值并将其添加到列表中,如下所示:

var selectedValues = from ListItem item in ListBox1.Items where item.Selected select item.Value;
var selectedStrings = selectedValues.ToList();

答案 4 :(得分:0)

你可以使用一个集合,例如List<String>存储值; Linq 可以非常方便地提供集合

  List<String> result = ListBox1.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Value).ToList();

使用Linq创建逗号分隔字符串也很容易:

  string CatID = String.Join(",", ListBox1.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Value));
相关问题