Click here to Skip to main content
15,890,670 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.
C#
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();
Posted
Updated 12-Nov-18 19:11pm

check you foreach loop. You are not adding Abbreviations in DataRow

C#
 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
 
Share this answer
 
Comments
TheBigBearNow 13-Nov-18 0:44am    
Thankyou !!
Is there an easy way to bind this to a combo box using IEnumerable and INotifyChange
[code]
public class US_State
{
public string Name { get; set; }

public string Abbreviations { get; set; }

public US_State()
{
Name = null;
Abbreviations = null;
}

public US_State(string ab, string name)
{
Name = name;
Abbreviations = ab;
}

public override string ToString()
{
return string.Format("{0} - {1}", Abbreviations, Name);
}
}
//STATIC ARRAY CLASS WHICH CONTAINS ALL THE STATE DATA.
public static class StateArray
{
static List<us_state> states;

static StateArray()
{
states = new List<us_state>(50);
states.Add(new US_State("AL", "Alabama"));
states.Add(new US_State("AK", "Alaska"));
states.Add(new US_State("AZ", "Arizona"));
states.Add(new US_State("AR", "Arkansas"));
states.Add(new US_State("CA", "California"));
states.Add(new US_State("CO", "Colorado"));
states.Add(new US_State("CT", "Connecticut"));
states.Add(new US_State("DE", "Delaware"));
states.Add(new US_State("DC", "District Of Columbia"));
states.Add(new US_State("FL", "Florida"));
states.Add(new US_State("GA", "Georgia"));
states.Add(new US_State("HI", "Hawaii"));
states.Add(new US_State("ID", "Idaho"));
states.Add(new US_State("IL", "Illinois"));
states.Add(new US_State("IN", "Indiana"));
states.Add(new US_State("IA", "Iowa"));
states.Add(new US_State("KS", "Kansas"));
states.Add(new US_State("KY", "Kentucky"));
states.Add(new US_State("LA", "Louisiana"));
states.Add(new US_State("ME", "Maine"));
states.Add(new US_State("MD", "Maryland"));
states.Add(new US_State("MA", "Massachusetts"));
states.Add(new US_State("MI", "Michigan"));
states.Add(new US_State("MN", "Minnesota"));
states.Add(new US_State("MS", "Mississippi"));
states.Add(new US_State("MO", "Missouri"));
states.Add(new US_State("MT", "Montana"));
states.Add(new US_State("NE", "Nebraska"));
states.Add(new US_State("NV", "Nevada"));
states.Add(new US_State("NH", "New Hampshire"));
states.Add(new US_State("NJ", "New Jersey"));
states.Add(new US_State("NM", "New Mexico"));
states.Add(new US_State("NY", "New York"));
states.Add(new US_State("NC", "North Carolina"));
states.Add(new US_State("ND", "North Dakota"));
states.Add(new US_State("OH", "Ohio"));
states.Add(new US_State("OK", "Oklahoma"));
states.Add(new US_State("OR", "Oregon"));
states.Add(new US_State("PA", "Pennsylvania"));
states.Add(new US_State("RI", "Rhode Island"));
states.Add(new US_State("SC", "South Carolina"));
states.Add(new US_State("SD", "South Dakota"));
states.Add(new US_State("TN", "Tennessee"));
states.Add(new US_State("TX", "Texas"));
states.Add(new US_State("UT", "Utah"));
states.Add(new US_State("VT", "Vermont"));
states.Add(new US_State("VA", "Virginia"));
states.Add(new US_State("WA", "Washington"));
states.Add(new US_State("WV", "West Virginia"));
states.Add(new US_State("WI", "Wisconsin"));
states.Add(new US_State("WY", "Wyoming"));
}

public static string[] Abbreviations()
{
List<string> abbrevList = new List<string>(states.Count);
foreach (var state in states)
CHill60 13-Nov-18 12:02pm    
Rather than adding an extra solution (which is confusing - which one is the solution you mean to use?), use the "Improve Solution" link and update that way
Based on your comment. practice following

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

C#
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
HTML
<ComboBox Name="cmboTest"
                 ItemsSource="{Binding USStates, RelativeSource={RelativeSource AncestorType=Window, Mode=FindAncestor}, UpdateSourceTrigger=PropertyChanged}"
                 DisplayMemberPath="Name" SelectedValuePath="Abbreviations" SelectionChanged="cmboTest_SelectionChanged"/>
 
Share this answer
 
Comments
TheBigBearNow 13-Nov-18 3:01am    
do i want to put
"private List<us_state> usStates;
public List<us_state> USStates
{
get
{
return usStates;
}
set
{
usStates = value;
RaisePropertyChanged();
}
}"

in my WPF window? or does that go in US_State class as well
I have the class made like you
im just not sure if i should make a new List<us_state> in my WPF window or if i should use that property
M.Kamran Asim 13-Nov-18 3:11am    
In above example I placed it in code behind of your window/userControl. It seems you are using window. So declare public property USStates in window code behind.
and on load method of window fill this property.
If you check xaml binding of combobox it says
Bind to USStates which is off course public property, but
Search in relatvie source which i guided as type of window and Find this type in Ancestor. means that in xaml document search its parent until you reach to type of window, and then search for the proerty USStates .
Lastly i mentioned as UpdateSourceTrigger=PropertyChanged. means if property changed, then trigger, so that I can update.
Therefore when you set USStates on windows load, chages will be automatically reflected to items source.

But I will suggest you to spend some time on MVVM (Mvvmlight is very simple and basic package)
TheBigBearNow 13-Nov-18 3:33am    
Thank you! I made a separate class US_States like you have and under that class at the bottom i made a public static class StatesArray
and in the statesarray class in the constructor I have
states.Add(new US_State("WY", "Wyoming"));
and this at bottom
public static US_State[] AllFiftyStates()
{
return states.ToArray();
}
I can make this in WPF window
private List<us_state> Get_States = StatesArray.states;
and combobox { Binding Get_States }

is that all correct?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900