简体   繁体   English

WPF C#组合框显示值

[英]WPF C# ComboBox Display Value

I can't be asking this question right. 我不能问这个问题。 I've asked it in 3 different forums and searched google for about a week now, and nothing. 我已经在3个不同的论坛中提出了要求,并且在Google上搜索了大约一个星期,现在什么也没有。 So let me try it again here and see if asking it a different way helps you help me... 因此,让我在这里再次尝试,看看是否以其他方式提出要求可以帮助您...

WPF C# MetroWindow using MahApps.Metro Window - Combobox - State Codes (50 US States) I created a dataset and dragged teh data set to the combo box in XAML. 使用MahApps.Metro窗口的WPF C#MetroWindow-组合框-状态代码(美国50个州)我创建了一个数据集并将数据集拖到XAML中的组合框中。 Here is the XAML 这是XAML

<ResourceDictionary>
    <CollectionViewSource x:Key="StatesViewSource" 
                          Source="{Binding States, Source={StaticResource PRx}}" />
</ResourceDictionary>

Inside the GRID I set the Data Context: 在GRID内部,我设置了数据上下文:

<Grid DataContext="{StaticResource StatesViewSource}">

Then the ComboBox 然后组合框

<ComboBox x:Name="CbState" 
      SelectedValuePath="StateCode" 
      ItemsSource="{Binding}"
      DisplayMemberPath="StateCode" />

Now, if that's it and I stop, it works. 现在,就是这样,我停止了,它可以正常工作。 I get the State Codes in the combobox; 我在组合框中找到了州代码; however, that's the not issue or the problem I need solved. 但是,这不是问题,也不是我需要解决的问题。 What I need to do is query the DB, find the patient, and return the address to the window. 我需要做的是查询数据库,找到患者,然后将地址返回到窗口。 Every field populates in the window except the Combobox. 除组合框外,每个字段都填充在窗口中。 It always defaults to the first state in the list - AL - value, even though the state code for the patient is MA. 即使患者的状态代码为MA,也始终默认为列表中的第一个状态-AL-值。

So, SQL works. 因此,SQL有效。 Combobox pulls values. 组合框提取值。 But I can't get the Combobox to default to MA as returned via the SQL. 但是我无法将组合框默认设置为通过SQL返回的MA。

Here is some C# Code that I'm using as well. 这也是我正在使用的一些C#代码。

private void ReturnPatient()
{
    var patIdReturn = TxtPatId.Text;
    var patSiteId = TxtTSiteCode.Text;
    var preSql = Settings.Default.GetPatientProfile;
    var param = " @p1 = '" + patIdReturn + "', @p2 = '" + patSiteId + "';";
    var sql = preSql + param;
    var connectionString = Settings.Default.Dbconn;
    using (var conn = new SqlConnection(connectionString))
    using (var cmd = new SqlCommand(sql, conn))
    {
        try
        {
            conn.Open();
            var reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                TxtFirstName.Text = reader[0] as string;
                TxtMi.Text = reader[1] as string;
                TxtLastName.Text = reader[2] as string;
                TxtLegacy.Text = reader[3] as string;
                DobPicker.SelectedDate = reader[4] as DateTime? ?? new DateTime();
                TxtPhone.Text = reader[5] as string;
                TxtAddr1.Text = reader[6] as string;
                TxtAddr2.Text = reader[7] as string;
                TxtCity.Text = reader[8] as string;
                TbState.Text = reader[9] as string;
                // trying a tbox instead of combobox, but this is where I want the Combobox for State. 
                TxtZip.Text = reader[10] as string;
                //break for single row or you can continue if you have multiple rows...
                break;
            }

            Log.Debug("Command executed and reader completed for ReturnPatient()");
        }
        catch (SqlException ex)
        {
            // error handling
        }
        finally
        {
            // logging
        }
    }
}

I have tried CbState.SelectedItem, CbState.SelectedValue, CbState.DisplayMemeber, etc... 我尝试了CbState.SelectedItem,CbState.SelectedValue,CbState.DisplayMemeber等...

Please, I know this has to be possible. 拜托,我知道这是必须的。 PLEASE HELP 请帮忙

Sincerely, 真诚的

Lost In ComboBox Hell :) 迷失在ComboBox地狱:)

It seems really simple matter and you're missing basic point. 看来这很简单,但您缺少基本要点。 If you click the combobox, can you see the 50 states names populated as bound items? 如果单击组合框,是否可以看到作为绑定项填充的50个州名称? As advised above, check the value of reader[9] is really MA. 如上所述,检查reader [9]的值确实是MA。 I recommend to try more specifically like reader["yourcolumnname"] to avoid confusion. 我建议尝试像reader [“ yourcolumnname”]这样更具体的方式以避免混淆。

And try CbState.SelectedText="MA"; 并尝试CbState.SelectedText =“ MA”;
or CbState.Text="MA"; 或CbState.Text =“ MA”;

The selected- prefix might mean it's the one which has to be selected intentionally by user. selected-前缀可能意味着它是用户必须有意选择的前缀。

And make sure in XML that selectedindex= -1. 并确保在XML中选择了index = -1。 If the index is = 0 , the combobox will consider the first populated item AL as default. 如果索引= 0,则组合框将默认第一个填充项AL。

As last, if you only have to put only already fixed 50 states names into combobox, why don't you simplify the code structure without binding like 最后,如果您只需要将已经固定的50个州名称放入组合框,为什么不简化代码结构而不进行绑定,例如

CbState.Items.Add("AL");
 ....
CbState.Items.Add("MA");
CbState.Items.Add("NY");

To computer, adding already fixed 50 names will be much more simple and faster than binding. 对于计算机,添加已经固定的50个名称比绑定要简单得多,而且速度更快。 If you don't need to do higher level works with binding. 如果您不需要做更高层次的绑定工作。

And as non-related minor issue, reader and connection should be closed in right manner. 作为无关紧要的小问题,应该以正确的方式关闭阅读器和连接。

cb_State.SelectedItem = (cb_State.ItemsSource as List<YourStateCodeClass>).Where(s=>s.StateCode == reader[9] as string).First();

but I don't see your StateCode class and yet you use DisplayMemberPath etc. 但我看不到您的StateCode类,但是您使用DisplayMemberPath等。

In case it is just strings you can use 如果只是字符串,您可以使用

cb_State.SelectedItem = (cb_State.ItemsSource as List<string>).Where(s => s == reader[9] as string).First();

and remove the DisplayMemberPath and SelectedValuePath 并删除DisplayMemberPathSelectedValuePath

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

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