簡體   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