2012-11-26 70 views
1

如何獲取列表框中所選項目的值?WPF Listbox SelectedItems

我想是這樣的:

  foreach (var item in combo_course_op.SelectedItems) 
      { 
       string s = "select cid from tms_course where course_title = '" + item.ToString() + "'"; 
      } 

但它不works..it顯示字符串s爲「選擇tms_course其中COURSE_TITLE = 'System.Data.DataRowView' CID」

我在哪裏做錯了?

這是我的數據怎麼綁定:

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

回答

1
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 
} 
+0

我試過了,但還沒有運氣;我編輯了這個問題,請查看 – iJay

+0

您是如何收到物品的。 (即combo_course_op.SelectedItems類型) – Tilak

+0

嗨tilak, 我將列表框更改爲列表視圖。我認爲我的數據綁定方法有一些錯誤。 列表 moduleNames = new List (); (MyReader.Read()) while(MyReader.Read()) { moduleNames.Add(MyReader.GetString(0)); } combo_course_op.ItemsSource = moduleNames; 現在你的方法很好... :) – iJay

-1

可以在其真正的類型轉換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組合框看起來像一個非常糟糕的ID。也許你應該閱讀一兩個關於WPF和MVVM的教程。

+0

事實上,將'DataRowView'放入WPF列表框是列表框數據綁定時.NET框架的默認行爲。 –

2

顯然你的列表框被綁定到某個數據源。這意味着列表框中的項目不是字符串,而是DataRowView的實例。你可以施放和得到的是底層的數據對象:

DataRowView drv = (DataRowView)item; 
<TheRealType> itemOfMyType = (<TheRealType>)drv.Row; 

其中<TheRealType>是該項目的實際數據類型被綁定到列表框中。

1

在你的代碼中的DisplayMemberPath設置成列[ 「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,所以你必須得到要返回的值的右列。

+0

你建議同樣的Tilak ..:D謝謝 – iJay

+0

沒有選擇,還沒有評論呢。你有module_name作爲列,他使用Title ...不確定是否會導致你的問題。只有49分,所以不能回覆評論和問。 – Zadam

+0

Y?不要..在他的文章中他提到了Title是什麼。 無論如何感謝:D祝你好運 – iJay