Reputation: 4293
how can I get the selected item's value of a list box?
I tried something like this:
foreach (var item in combo_course_op.SelectedItems)
{
string s = "select cid from tms_course where course_title = '" + item.ToString() + "'";
}
but it doesnt works..it shows string s as "select cid from tms_course where course_title ='System.Data.DataRowView'"
where am I doing wrong?
This is how I data binded:
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();
Upvotes: 1
Views: 4529
Reputation: 434
In your code the DisplayMemberPath is set to Columns["module_name"]
Inferring from this, following should work:
foreach (var item in combo_course_op.SelectedItems)
{
string s = "select cid from tms_course where course_title = '" + item["module_name"].ToString() + "'";
}
Selected items are DataRow, therefore you have to get the right column for the value to be returned.
Upvotes: 1
Reputation: 30728
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
}
Upvotes: 1
Reputation: 56727
Obviously your list box is bound to some data source. That means that the items in the list box are not strings, but instances of DataRowView
. You can cast and get the underlying data object like that:
DataRowView drv = (DataRowView)item;
<TheRealType> itemOfMyType = (<TheRealType>)drv.Row;
where <TheRealType>
is the actual data type of the item being bound to the list box.
Upvotes: 2
Reputation: 9265
You can cast Item
in its real type :
foreach (var item in combo_course_op.SelectedItems)
{
string s = "select cid from tms_course where course_title = '" +
((Course)item).Title + "'";
}
Or override Course.ToString
so it return its title.
EDIT (after noticed about DataRowView
)
Putting DataRowViews in a WPF ComboBox looks like a really bad id. Maybe you should read a tutorial or two about WPF and MVVM.
Upvotes: -1