ASP.. NET列表框未选择多个值

本文关键字:选择 NET 列表 ASP | 更新日期: 2023-09-27 18:16:20

我在我的webform中有一个列表框,我试图从中选择多个值,但我只得到最后选择的值。我试过两种方法。首先,我显式地添加了列表项:

<asp:ListBox ID="ListBox2" runat="server" 
    SelectionMode="Multiple" AutoPostBack="True">
    <asp:ListItem>teama</asp:ListItem>
    <asp:ListItem>teamb</asp:ListItem> 
</asp:ListBox>

第二,我尝试绑定到数据库中的表:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ListBox2.SelectionMode = ListSelectionMode.Multiple;
        string scon = ConfigurationManager.ConnectionStrings["Test_AthiraConnectionString"].ConnectionString;
        SqlConnection con=new SqlConnection(scon);
        con.Open();
        SqlCommand cmd = new SqlCommand("select department from department", con);
        cmd.CommandType = CommandType.Text;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        ListBox2.DataSource = ds;
        ListBox2.DataValueField = "department";
        ListBox2.DataTextField = "department";
        ListBox2.DataBind();
        con.Close();
    }
}

然后我尝试了这些不同的方法来选择buttonclick event上的多个项目

:

string k =null ,k1 = null;
foreach (int i in ListBox2.GetSelectedIndices())
{
    k1 = ListBox2.Items[i].Text + "/";
    k += k1;
    Response.Write(k);
}
第二:

foreach (ListItem li in ListBox2.Items)
{
    if (li.Selected == true)
    {
        k += li.Text + "/";
        Response.Write(k);
    }
}
第三:

k = String.Join("/", ListBox2.Items
                             .Cast<ListItem>()
                             .Where(i => i.Selected)
                             .Select(i=>i.Value)
                             .ToArray());
Response.Write(k);
第四:

for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
{
    if (ListBox2.Items[i].Selected == true)
    {
        k1 = ListBox2.Items[i].Text + "/";
        k += k1;
        Response.Write(k);
    }
}

但是它们似乎都不起作用。我只得到最后选择的值

ASP.. NET列表框未选择多个值

您可以如下方式访问列表中的项并检查它们的属性。

    IEnumerator ie =  ListBox2.Items.GetEnumerator();
    while (ie.MoveNext())
    {
        ListItem li = (ListItem)ie.Current;
        //Use ListItem here
    }    

请尝试下面的代码,它将返回逗号分隔字符串为列表框选定的值

  public string GetSelectedValues()
    {
        string selectedVal = string.Empty;
        int i = 0;
        foreach (int index in lstbox.GetSelectedIndices())
        {
            if (i == 0) 
               selectedVal = lstbox.Items[index].Value;
            else
              selectedVal = selectedVal + ";" + lstbox.Items[index].Value.ToString();
            i++;
        }
        return selectedVal ;
    }