WPF 组合框选择名称使用 ID

问题描述 投票:0回答:1

我有一个

ComboBox
,我尝试在其中使用名称,但是当用户选择名称时,我想选择 ID 而不是名称。

这是我的 XAML:

<ComboBox x:Name="cb_tvrtkaID" Height="25" Margin="0,10,0,0" Loaded="cb_tvrtkaID_Loaded"/>

还有我的 C#:

private void cb_tvrtkaID_Loaded(object sender, RoutedEventArgs e) {
    MSSQLConnect sql = new MSSQLConnect();
    bool sqlIsConnected = sql.Connect();
    string query = "SELECT tvrtkaId,tvrtkaNaziv from sifarnik.tvrtka";
    SqlConnection connection = sql.GetConnection();
            
    if (connection != null) {
        using (connection) {
            try {
                SqlCommand cmd = new SqlCommand(query, connection);
                SqlDataReader reader = cmd.ExecuteReader();
                    
                if (reader.HasRows) {
                    while (reader.Read()) {
                        cb_tvrtkaID.Items.Add(reader["tvrtkaNaziv"].ToString());
                        //cb_tvrtkaID.Items.Add(reader["tvrtkaId"].ToString());
                        cb_tvrtkaID.SelectedItem = reader["tvrtkaId"].ToString();
                        cb_tvrtkaID.DisplayMemberPath = reader["tvrtkaNaziv"].ToString();

                    }
                }
            }
            catch (Exception ex) {
                Debug.WriteLine(ex);
            }
        }
    }
}

这给了我以下错误:

System.Windows.Data Error: 40 : BindingExpression path error: 'Arbet-grad d' property not found on 'object' ''String' (HashCode=-1526763463)'. BindingExpression:Path=Arbet-grad d.o.o.; DataItem='String' (HashCode=-1526763463); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

System.Windows.Data Error: 40 : BindingExpression path error: 'Arbet-grad d' property not found on 'object' ''String' (HashCode=1553220975)'. BindingExpression:Path=Arbet-grad d.o.o.; DataItem='String' (HashCode=1553220975); target element is 'ComboBox' (Name='cb_tvrtkaID'); target property is 'NoTarget' (type 'Object')

如何解决此错误,以便显示名称但选择基础 ID?

c# wpf data-binding app.xaml
1个回答
1
投票

一般来说,我建议用包含名称和 ID 的对象填充组合框。然后配置您的组合框以显示对象的名称。

 <ComboBox x:Name="cb_tvrtkaID" Height="25" Margin="0,10,0,0" Loaded="cb_tvrtkaID_Loaded">
       <ComboBox.ItemTemplate>
               <DataTemplate>
                   <TextBlock Text="{Binding Name}" />
               </DataTemplate>
       </ComboBox.ItemTemplate>
   </ComboBox>

组合框中的对象将由以下方式定义:


  class cbItem
   {
      public string Name{get;set;}
      public string ID;
      public cbItem(string name, string id)
      { Name=name; ID=id;}
   }

在您的代码中,您可以添加以下项目:

 //[...]
   while (reader.Read())
      {
         cbItem myCbItem = new cbItem(reader["tvrtkaNaziv"].ToString(), reader["tvrtkaId"].ToString();
         cb_tvrtkaID.Items.Add(myCbItem );
         
         //from outside this method, you can find the item of your combobox whose ID property is x, simply by iterating or with the help of Linq
         cb_tvrtkaID.SelectedItem = myCbItem;
      }

//[...]

每次使用

cb_tvrtkaID.Items.Clear()
从 SQL 加载时,不要忘记清理组合框项目。

例如,您可以使用绑定到

cbItem
列表和转换器来实现与上述相同的结果

© www.soinside.com 2019 - 2024. All rights reserved.