Listbox in asp.net not getting selected items

我是研究僧i 提交于 2019-12-01 09:41:27

You are setting it to the same value every time:

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

When you actually want the value of the item in your loop that is selected:

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

I am not sure what is wrong with the logic i am using.

I came across a nice solution using LINQ.

This single statement works great & gets me the desired results.

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

RESULT: 3,29,25

Try to add Page.IsPostback on your Page_Load like

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)
    {

    }
}

Code:

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);
}

Once i was facing the same problem and i made Postback mistake.

Hope it works.

Get the selected items using linq

var selected = lstCatID.Items.Where(i => i.Selected);

Minutes later I found a solution:

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

This worked fine in my scenario

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!