3

我的网页中有多个下拉列表和列表框。

我正在尝试CategoryIDlstCatID列表框中获取列表,我可以使用类别名称填充列表框。

如果我在第一次尝试时没记错,我的代码运行良好,之后我做了一些更改,然后它声明总是选择第一个项目 x 时间

<asp:ListBox ID="lstCatID" runat="server" DataTextField="CategoryName" 
                DataValueField="CategoryID" SelectionMode="Multiple" CssClass="lstListBox">
 </asp:ListBox>



protected void Button1_Click(object sender, EventArgs e)
{
    string CatID = string.Empty;
    foreach (ListItem li in lstCatID.Items)
    {
        if (li.Selected == true)
        {
           // Response.Write();
            CatID += lstCatID.SelectedItem.Value + ",";
        }
    }
    Response.Write(CatID);
}

我不确定出了什么问题,我检查了 MSDN,它显示了完全相同的方法。

可能是我做错了什么。

只是使用 Firefox 添加我能够看到多个选定的值具有选定的属性。

<option value="3" selected="selected">One</option>
<option value="2">Two</option>
<option value="29" selected="selected">Three</option>
<option value="25" selected="selected">Four</option>
<option value="22" >Five</option>

在这种情况下,我的输出将是3,3,3

我将不胜感激这方面的帮助

4

5 回答 5

8

我不确定我使用的逻辑有什么问题。

我遇到了一个使用 LINQ 的不错的解决方案。

这个单一的陈述效果很好,让我得到了想要的结果。

string values = String.Join(", ", lstCatID.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value).ToArray());

结果:3,29,25

于 2013-05-02T13:09:03.407 回答
7

您每次都将其设置为相同的值:

foreach (ListItem li in lstCatID.Items)
{
    if (li.Selected == true)
    {
       // you are always using lstCatID.SelectedItem.Value.
        CatID += lstCatID.SelectedItem.Value + ",";
    }
}

当您真正想要选择的循环中项目的值时:

foreach (ListItem li in lstCatID.Items)
{
    if (li.Selected == true)
    {
        // get the value of the item in your loop
        CatID += li.Value + ",";
    }
}
于 2013-05-02T13:11:51.430 回答
4

尝试在您的 Page_Load 上添加Page.IsPostback

protected void Page_Load(object sender, EventArgs e)
{
    // Do your API code here unless you want it to occur only the first
    // time the page loads, in which case put it in the IF statement below.
    if (!Page.IsPostBack)
    {

    }
}

代码:

protected void Button1_Click(object sender, EventArgs e)
{
    string CatID = string.Empty;
    foreach (ListItem li in lstCatID.Items)
    {
        if (li.Selected )
        {
           // TODO: Whatever you are doing with a selected item.
        }
    }
    Response.Write(CatID);
}

一旦我遇到同样的问题并且我犯了回发错误。

希望它有效。

于 2013-05-02T12:41:50.663 回答
2

使用 linq 获取所选项目

var selected = lstCatID.Items.Where(i => i.Selected);
于 2013-09-23T08:58:45.080 回答
0

几分钟后,我找到了解决方案:

If lstLocations.Items.Count > 0 Then
            For i As Integer = 0 To lstLocations.Items.Count - 1
                If lstLocations.Items(i).Selected Then
                    'insert command
                    Dim selectedItem As String = lstLocations.Items(i).Text
                End If
            Next
        End If

这在我的场景中效果很好

于 2016-08-19T14:53:10.433 回答