我不能正确地问这个问题。我已经在3个不同的论坛上问过它,现在搜索谷歌大约一个星期了,什么都没有。所以,让我在这里再试一次,看看是否以不同的方式帮助你帮助我...
使用MahApps.Metro的WPF C#MetroWindow Window - Combobox - 州代码(美国50个州) 我创建了一个数据集并将数据集拖到XAML中的组合框中。 这是XAML
<ResourceDictionary>
<CollectionViewSource x:Key="StatesViewSource"
Source="{Binding States, Source={StaticResource PRx}}" />
</ResourceDictionary>
在GRID内部,我设置了数据上下文:
<Grid DataContext="{StaticResource StatesViewSource}">
然后是ComboBox
<ComboBox x:Name="CbState"
SelectedValuePath="StateCode"
ItemsSource="{Binding}"
DisplayMemberPath="StateCode" />
现在,如果就是这样,我停下来就行了。我在组合框中得到了州代码;然而,这不是我需要解决的问题或问题。我需要做的是查询数据库,找到患者,并将地址返回到窗口。除Combobox外,每个字段都在窗口中填充。它总是默认为列表中的第一个状态 - AL - 值,即使患者的状态代码是MA。
所以,SQL有效。 Combobox提升了价值。但是我无法通过SQL返回将Combobox默认为MA。
这是我正在使用的一些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
}
}
}
我试过CbState.SelectedItem,CbState.SelectedValue,CbState.DisplayMemeber等...
拜托,我知道这一定是可能的。请帮助
此致
迷失在ComboBox地狱:)
答案 0 :(得分:0)
这似乎很简单,你错过了基本观点。如果单击组合框,您是否可以看到填充为绑定项的50个州名称?如上所述,检查阅读器[9]的值是否真的是MA。我建议尝试更具体的读者[&#34; yourcolumnname&#34;]以避免混淆。
然后尝试CbState.SelectedText =&#34; MA&#34 ;;
或CbState.Text =&#34; MA&#34 ;;
所选前缀可能意味着它必须由用户有意选择。
并在XML中确保selectedindex = -1。 如果索引为= 0,则组合框将第一个填充的项目AL视为默认值。
最后,如果您只需要将已修复的50个州名称放入组合框中,为什么不简化代码结构而不绑定
CbState.Items.Add("AL");
....
CbState.Items.Add("MA");
CbState.Items.Add("NY");
对于计算机,添加已修复的50个名称将比绑定更简单,更快捷。如果你不需要用绑定做更高级别的工作。
作为非相关的小问题,读者和连接应该以正确的方式关闭。
答案 1 :(得分:0)
cb_State.SelectedItem = (cb_State.ItemsSource as List<YourStateCodeClass>).Where(s=>s.StateCode == reader[9] as string).First();
但是我没有看到你的StateCode类,但是你使用了DisplayMemberPath
等。
如果它只是字符串,您可以使用
cb_State.SelectedItem = (cb_State.ItemsSource as List<string>).Where(s => s == reader[9] as string).First();
并删除DisplayMemberPath
和SelectedValuePath