繁体   English   中英

在C#中的列表框中获取所选项目的索引

[英]Getting the indexes of selected items in a listbox in C#

我用这样的表中的一些值填充列表框:

    private void LoadFunctions()
    {
        using (SqlConnection con = new SqlConnection(str2))
        {

            try
            {
                string strSQL = "Select [Function_ID], [Function_DESC] from [MOS_Function];";

                SqlDataAdapter adapter = new SqlDataAdapter(strSQL, con);
                DataSet DDLFunction = new DataSet();
                adapter.Fill(DDLFunction);

                cboFunction.DataSource = DDLFunction;
                cboFunction.DataTextField = "Function_DESC";
                cboFunction.DataValueField = "Function_ID";
                cboFunction.DataBind();

                cboFunction.Items.Insert(0, new ListItem("Select All", "0"));
                ////  ddlRole.Items.Insert(0, new ListItem("Select your role", "0"));
            }
            catch (Exception ae)
            {
                Response.Write(ae.Message);
            }
        }
    }

我有一些代码,可以为我提供一个包含多选列表框中所有选定项的字符串(Function_DESC):

  // Read the selected items from the listbox
  var selectedFunctions = cboFunction.Items.Cast<ListItem>().Where(item => item.Selected);
  string txtFunctions = String.Join(",", selectedFunctions).TrimEnd();

奇迹般有效。 但是,现在我想将Function_ID放在txtFunctions字符串中。 我是C#的新手,我看过一些示例,但是我不知道如何编辑必须正常工作的内容。

您只需要在item.Value上添加Select到LINQ的当前结果

var selectedFunctions = cboFunction.Items.Cast<ListItem>()
                                   .Where(item => item.Selected)
                                   .Select (item => item.Value);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM