我正在填充列表框,其中包含以下表格中的某些值:
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#比较陌生,我已经看过一些例子,但我无法弄清楚如何编辑我必须正常工作的内容。
答案 0 :(得分:1)
您只需要在Select
上添加item.Value
到LINQ的当前结果
var selectedFunctions = cboFunction.Items.Cast<ListItem>()
.Where(item => item.Selected)
.Select (item => item.Value);