2012-06-06 44 views
0

我有两个表。 Table1通过Table2ID与Table2链接。WPF组合框将SQL与selectedValue绑定为数据库

我需要一个组合框来加载Table2中的所有数据并显示如表1所示的初始选择。

下面的代码只能加载从表2的所有数据,但无法显示选择如表1所示

任何一个能帮助我吗? 谢谢。

enter image description here 在此图片中,当窗口第一次加载时,组合框应显示“Swan Wan Trading”。

Table1 
ID Name Table2ID 
1 Hello 1 
2 World 1 
3 User 2 

Table2 
ID Name 
1 ABC 
2 DEF 

private DataSet getData() 
     { 
      SqlConnection conn = new SqlConnection(ConnectionString); 
      SqlDataAdapter da = new SqlDataAdapter("usp_getalldata", conn); 
      DataSet ds = new DataSet(); 
      da.Fill(ds, "DATA"); 
      return ds; 
     } 
public Details() 
    { 
     InitializeComponent(); 
     DataSet ds = getData(); 
     DataTable dt = ds.Tables[0]; 
     this.combobox.ItemsSource = ((IListSource)dt).GetList(); 
     this.combobox.DisplayMemberPath = "Name"; 
     this.combobox.SelectedValuePath = "ID"; 
} 

回答

0
this.combobox.SelectedValue = Table2ID; 

使用上述和它的工作。 感谢您的协助。

1

不应该将ObjectDataProvider为您ComboBox在你的XAML的ItemsSource

下面是一个如何使用它的例子。

<UserControl.Resources> 
    <ObjectDataProvider x:Key="MyDataSource" ObjectType="{x:Type my:StaticDataSource}" MethodName="GetMyData"/> 
</UserControl.Resources> 

... 

<ComboBox ItemsSource="{Binding Source={StaticResource MyDataSource}}" SelectedValue="{Binding Table2ID}"/> 

StaticDataSource类看起来是这样的:

public class MyDataSource 
{ 
    private static IEnumerable<Table2> myData; 

    public MyDataSource(IEnumerable<Table2> data) 
    { 
     myData = data; 
    } 

    public static IEnumerable<Table2> GetMyData() 
    { 
     return myData; 
    } 
} 
+0

嗨Guillaume,我能够显示组合框中的Table2记录,但我需要显示在Table1的Table2ID中的comboxbox初始选定值。 – kyusan93

+0

您需要将'ComboBox'的'SelectedValue'或'SelectedItem'属性绑定到'Table1'对象的相应属性。你的问题中没有这样的事情。 – Guillaume