简体   繁体   中英

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. 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. Here is the XAML

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

Inside the GRID I set the Data Context:

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

So, SQL works. Combobox pulls values. But I can't get the Combobox to default to MA as returned via the SQL.

Here is some C# Code that I'm using as well.

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

Please, I know this has to be possible. PLEASE HELP

Sincerely,

Lost In ComboBox Hell :)

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? As advised above, check the value of reader[9] is really MA. I recommend to try more specifically like reader["yourcolumnname"] to avoid confusion.

And try CbState.SelectedText="MA";
or CbState.Text="MA";

The selected- prefix might mean it's the one which has to be selected intentionally by user.

And make sure in XML that selectedindex= -1. If the index is = 0 , the combobox will consider the first populated item AL as default.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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