Combobox从数据表选择所选项目填充 [英] Combobox populated from datatable select selected item
问题描述
大家好,我有一个简单的问题,这对你们大多数人来说很简单,但由于某些原因,我一直没有任何问题,只能解决问题。
我有一个组合框是填充了具有2个属性的对象的数据表。当我在组合框中选择某个项目时,我想获取其中一个属性的值。这是我的类和代码,用于创建数据表和xaml。
private void BindComboBoxStates()
{
DataView dataview = dataSetStates.Tables [ 0 ]。DefaultView;
ComboboxState.ItemsSource = dataview;
ComboboxState.DisplayMemberPath = dataSetStates.Tables [ 0 ]。列[ 名称跨度>]的ToString();
ComboboxState.SelectedValuePath = dataSetStates.Tables [ 0 ]。列[ 缩写跨度>]的ToString();
}
private void CreateDataTableStates()
{
DataTable dataTableStates = new DataTable( States跨度>);
dataTableStates.Columns.AddRange( new DataColumn []
{
new DataColumn( 名称, typeof ( string )),
new DataColumn( 缩写, typeof ( string ))
});
foreach (US_State st in StateArray.States())
{
dataTableStates.Rows.Add(st.Name);
}
dataSetStates.Tables.Add(dataTableStates);
}
< ComboBox x:Name = ComboboxState Grid.Column = 1 Grid.Row = 2 VerticalAlignment = 中心宽度= 120 HorizontalAlignment = Left ToolTip = 输入您的州。
/>
<! - ItemsSource = {Binding Path = states} DisplayMemberPath = < span class =code-string> 名称 SelectedValuePath = 缩写 - >
// 这是我一直在尝试选择项目的地方
// var state = ComboboxState.SelectedValue; // ComboboxState.SelectedValue.ToString();
// var state =((ComboBoxItem)ComboboxState.SelectedItem).Content.ToString();
// as ComboBoxItem)//。GetValue.ToString();
< span class =code-keyword> var cb =(sender as ComboBox);
var selectedItem =(cb.SelectedItem as DataRowView);
// cb.SelectedItem [Abbreviations]。ToString();
我尝试了什么:
尝试过多少获取所选值的方法
// var state = ComboboxState.SelectedValue; // ComboboxState.SelectedValue.ToString();
// var state =((ComboBoxItem)ComboboxState.SelectedItem).Content.ToString();
//作为ComboBoxItem)//。GetValue.ToString();
var cb =(发送者为ComboBox);
var selectedItem =(cb.SelectedItem as DataRowView);
//cb.SelectedItem [\"Abbreviations\"].ToString();
检查你的foreach循环。你没有在DataRow中添加缩写
foreach (US_State st < span class =code-keyword> in StateArray.States())
{
dataTableStates.Rows.Add(st.Name);
// 这应该是bedataTableStates.Rows.Add(st.Name,st.Abbrivation);
}
现在在选择更改时,在selectedItem属性中你可以获得Name + abbrivation或者你可以获得SelectedValue
根据您的评论。练习以下
public class US_State:System.ComponentModel.INotifyPropertyChanged
{
string name;
string 缩写;
public string 名称{ get {返回名称; } set {name = value ; RaisePropertyChanged(); }
public string 缩写{获取 {返回缩写; } set {abbreviations = value ; RaisePropertyChanged(); }
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string name = )
{
PropertyChanged?.Invoke( this , new PropertyChangedEventArgs(name));
}
}
注意:在你的情况下你不需要INotifyPropertyChange用于US_State。我添加了它,如果你将来需要2路绑定。你可以像你一样创建计划属性
现在你已经完成了。在ViewModel中创建ObservableCollection或Us_State列表(如果您使用的是MVVM)。为简单起见,我将在后面的代码中创建List,例如
private List< ; US_State> usStates;
public 列表< US_State> USStates
{
get
{
return usstates ;
}
set
{
usStates = value ;
RaisePropertyChanged();
}
}
现在分配USStates = StateArray.states;但是要在静态类中公开状态。现在最终绑定有点棘手
在这个例子中,我已经在windows /用户控件代码中声明了UsStates,所以你必须引导将itemssource绑定到位于userControl内的USStates的组合框。 (不要说所有的内容控件都会查看datacontext)
看看下面的xaml
< ComboBox 名称 = cmboTest
ItemsSource = {绑定USStates,RelativeSource = {RelativeSource AncestorType = Window,Mode = FindAncestor},UpdateSourceTrigger = PropertyChanged}
产品详细显示layMemberPath = 名称 SelectedValuePath = 缩写 SelectionChanged = cmboTest_SelectionChanged / >
Hello all I have s simple question well this is simple for probably the most of you but for some reason, I have been having nothing but problems figuring it out.
I have a combobox that is filled with a datatable of a object with 2 properties. I would like to get the value of one of the properties when I select a certain item in the combo box. Here is my class and code that creates the datatable and xaml.
private void BindComboBoxStates()
{
DataView dataview = dataSetStates.Tables[0].DefaultView;
ComboboxState.ItemsSource = dataview;
ComboboxState.DisplayMemberPath = dataSetStates.Tables[0].Columns["Name"].ToString();
ComboboxState.SelectedValuePath = dataSetStates.Tables[0].Columns["Abbreviations"].ToString();
}
private void CreateDataTableStates()
{
DataTable dataTableStates = new DataTable("States");
dataTableStates.Columns.AddRange(new DataColumn[]
{
new DataColumn("Name", typeof(string)),
new DataColumn("Abbreviations", typeof(string))
});
foreach(US_State st in StateArray.States())
{
dataTableStates.Rows.Add(st.Name);
}
dataSetStates.Tables.Add(dataTableStates);
}
<ComboBox x:Name="ComboboxState" Grid.Column="1" Grid.Row="2" VerticalAlignment="Center" Width="120" HorizontalAlignment="Left" ToolTip="Enter your state."
/>
<!-- ItemsSource="{Binding Path=states}" DisplayMemberPath="Name" SelectedValuePath="Abbreviations" -->
//And here is where I have been trying to select the item
//var state = ComboboxState.SelectedValue;//ComboboxState.SelectedValue.ToString();
//var state = ((ComboBoxItem)ComboboxState.SelectedItem).Content.ToString();
// as ComboBoxItem)//.GetValue.ToString();
var cb = (sender as ComboBox);
var selectedItem = (cb.SelectedItem as DataRowView);
//cb.SelectedItem["Abbreviations"].ToString();
What I have tried:
tried lots of ways to get the selected value
//var state = ComboboxState.SelectedValue;//ComboboxState.SelectedValue.ToString(); //var state = ((ComboBoxItem)ComboboxState.SelectedItem).Content.ToString(); // as ComboBoxItem)//.GetValue.ToString(); var cb = (sender as ComboBox); var selectedItem = (cb.SelectedItem as DataRowView); //cb.SelectedItem["Abbreviations"].ToString();
check you foreach loop. You are not adding Abbreviations in DataRow
foreach(US_State st in StateArray.States()) { dataTableStates.Rows.Add(st.Name); //this should bedataTableStates.Rows.Add(st.Name,st.Abbrivation); }
Now On selection change, In selectedItem property You can get Name + abbrivation or you can get SelectedValue
Based on your comment. practice following
public class US_State : System.ComponentModel.INotifyPropertyChanged { string name; string abbreviations; public string Name { get { return name; } set { name = value; RaisePropertyChanged(); } } public string Abbreviations { get { return abbreviations; } set { abbreviations = value; RaisePropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string name="") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } }
NOTE: In your case you dont need INotifyPropertyChange for US_State. I added it, if you need 2 way binding in future. You can Create plan properties as you did it
Now you are all set. Create ObservableCollection or List of Us_State in ViewModel (if you are using MVVM). for simplicity I will create List in code behind like
private List<US_State> usStates; public List<US_State> USStates { get { return usStates; } set { usStates = value; RaisePropertyChanged(); } }
Now assign USStates = StateArray.states; but make states public in your static class. Now final binding is little bit tricky
As in this example I have declared UsStates in windows/user controls code behind, So you have to guide combobox that bind itemssource to USStates which is placed inside userControl. (Be defauly all content controls looks into datacontext)
have a look of following xaml
<ComboBox Name="cmboTest" ItemsSource="{Binding USStates, RelativeSource={RelativeSource AncestorType=Window, Mode=FindAncestor}, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Name" SelectedValuePath="Abbreviations" SelectionChanged="cmboTest_SelectionChanged"/>
这篇关于Combobox从数据表选择所选项目填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!