简体   繁体   English

WPF Combobox Select 名称使用ID

[英]WPF Combobox Select Name use ID

I have a ComboBox , and I am trying to use names in it, but when the user selects a name, I want to select an ID instead of the name.我有一个ComboBox ,我试图在其中使用名称,但是当用户选择一个名称时,我想 select 一个 ID 而不是名称。

Here's my XAML:这是我的 XAML:

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

And my C#:还有我的 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);
            }
        }
    }
}

This gives me the following error:这给了我以下错误:

System.Windows.Data Error: 40: BindingExpression path error: 'Arbet-grad d' property not found on 'object' ''String' (HashCode=-1526763463)'. BindingExpression:Path=Arbet-grad doo; 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 doo; DataItem='String' (HashCode=1553220975); target element is 'ComboBox' (Name='cb_tvrtkaID'); target property is 'NoTarget' (type 'Object')

How can I resolve this error, so that a name is displayed but the underlying ID is selected?如何解决此错误,以便显示名称但选择基础 ID?

In general, what I would suggest is to populate your combobox with objects that contain name and ID.一般来说,我建议使用包含名称和 ID 的对象填充 combobox。 Then configure your combobox to show the name of the object.然后配置您的 combobox 以显示 object 的名称。

 <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>

The objects in the combobox would be defined by: combobox 中的对象将定义为:


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

And in your code, you would add the items like:在您的代码中,您将添加以下项目:

 //[...]
   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;
      }

//[...]

Don't forget to clean the combobox items every time that you load from the SQL using cb_tvrtkaID.Items.Clear() .每次使用cb_tvrtkaID.Items.Clear()从 SQL 加载时,不要忘记清理 combobox 项目。

You can accomplish the same results above using a binding to a list of cbItem s and a converter, for example您可以使用绑定到cbItem列表和转换器来完成上述相同的结果,例如

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM