简体   繁体   中英

Getting the indexes of selected items in a listbox in C#

I'm filling a listbox with some values from a table like this:

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

I've got some code that gives me a string with all selected items (Function_DESC) in a multi-select listbox:

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

Works like a charm. However, now I want to put the Function_ID in the txtFunctions string instead. I'm relatively new to C# and I've seen a few examples but I can't figure out how to edit what I have to work properly.

You just need to add Select on the item.Value to the current result of your LINQ

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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