[英]WPF Listbox SelectedItems
如何获取所选项目的列表框值?
我试过这样的事情:
foreach (var item in combo_course_op.SelectedItems)
{
string s = "select cid from tms_course where course_title = '" + item.ToString() + "'";
}
但它不起作用..它将字符串s显示为“从tms_course中选择cid,其中course_title ='System.Data.DataRowView'”
我哪里做错了?
这是我数据绑定的方式:
MyCommand = new OdbcCommand("select distinct module_name from tms_class_schedule where class_date ='"+selectedDate+"'", DBConnect.MyConnection);
dap = new OdbcDataAdapter(MyCommand);
DS = new DataSet();
dap.SelectCommand = MyCommand;
dap.Fill(DS);
combo_course_op.DataContext = DS.Tables[0].DefaultView;
combo_course_op.DisplayMemberPath = DS.Tables[0].Columns["module_name"].ToString();
显然,您的列表框绑定到某些数据源。 这意味着列表框中的项不是字符串,而是DataRowView
实例。 您可以像这样强制转换和获取基础数据对象:
DataRowView drv = (DataRowView)item;
<TheRealType> itemOfMyType = (<TheRealType>)drv.Row;
其中<TheRealType>
是绑定到列表框的项目的实际数据类型。
foreach (var item in combo_course_op.SelectedItems)
{
string s = "select cid from tms_course where course_title = '"
+ (item["Title"] as string) + "'"; // if Title is column name. Otherwise replace "Title" with actual column header name
}
在您的代码中,DisplayMemberPath设置为Columns [“module_name”]
推断,以下应该工作:
foreach (var item in combo_course_op.SelectedItems)
{
string s = "select cid from tms_course where course_title = '" + item["module_name"].ToString() + "'";
}
所选项目是DataRow,因此您必须获取要返回的值的正确列。
您可以在其实际类型中强制转换Item
:
foreach (var item in combo_course_op.SelectedItems)
{
string s = "select cid from tms_course where course_title = '" +
((Course)item).Title + "'";
}
或者覆盖Course.ToString
,使其返回标题。
编辑 (关注DataRowView
)
将DataRowViews放在WPF ComboBox中看起来非常糟糕。 也许你应该阅读一两篇关于WPF和MVVM的教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.