none
Silverlight Combobox seleteditem.

    General discussion

  • Using EF4 + DDS,SL5

    I have a combobox in XAML and in loaded event I was trying to set the selelcteditem  as defualt.

    I just want to set combobox seleted item when it loads...

    what I try is : 1)  cbo.seleteditem = "Test";

    2) cbo.seleteditem =ptx.entity.select(0=>o.entitycolumn);

    3)

    List<LanguageList> AppLanguages = LanguageComboBox.ItemsSource as List<LanguageList>;
    var selectedLanguage = (from o in AppLanguages where o.LanguageCode == "en-US" select o).FirstOrDefault();
    LanguageComboBox.SelectedItem = selectedLanguage;

    4) seleteditem.seletecvalue ,selectedvaluepath,selectedindex=0,-1,-2,1,everything.


    but still not working....
    Tuesday, April 10, 2012 2:53 PM

All replies

  • Try making properties in your xaml backing code class for the ItemsSource and the SelectedItem.  Then bind to those properties in the xaml and then set the properties of the class instead of the control.

    Be sure to implement INotifyPropertyChanged.

    Tuesday, April 10, 2012 4:17 PM
  • I don't have any INotifyPropertyChanged in my code behind.(I am doing two way binding)

    I have a simple xaml page which contains a combobox(say I want to display column c from table 1) that's it!

    in code behind what I was trying is :

       private void cbo_Loaded(object sender, RoutedEventArgs e)


    {            pcontext ptx =(PContext)pDomainDataSource.DomainContext;
                Binding itemsSource = new Binding("entitys") { Source = this.pDomainDataSource.DomainContext };
                Binding SelectedItem = new Binding("entity") { Mode = BindingMode.TwoWay };//ItemsSource="{Binding Source=entity.entityname Path=Data}"
                cbo.SetBinding(ComboBox.ItemsSourceProperty, itemsSource);
                cbo.SetBinding(ComboBox.SelectedItemProperty, SelectedItem);
                cbo.DisplayMemberPath = "column c"; //{ DisplayMemberPath = "column c"};  

                //cbo.SelectedValue= cbo.Items.SingleOrDefault(c => (c as ComboBoxItem).Content == "comboboxitem");

               /// cbo.SelectedValue=cbo.Items[1];

                
                //cbo.Items.IndexOf("comboboxitem");
                
                
                //cbo.SelectedValuePath = "665";
               
               // cbo.SelectedIndex = 0;
                //Web.entityselectedProject = (from p in ptx.entityselect p).FirstOrDefault();
                //IEnumerable<FMProject> projectList = PDataGrid.ItemsSource.OfType<entity>();
                //List<Web.entity> projectList = cbo.DataContext as List<Web.entity>;
                //MessageBox.Show(projectList.First().ToString());
                //Web.entity.selectedProject = (from p in projectList where p.column c== "string" select p).FirstOrDefault();

                
                //cbo.SelectedItem = ptx.entities.Select(o=>o.column c);
                //cbo.SelectedItem = selectedProject;
              
                
                //cbo.SelectedItem = "string";

              //  PContext ptx =(PContext)pDomainDataSource.DomainContext;

                //List<entity> AppLanguages = cbo.ItemsSource as List<entity>;
              //var selectedLanguage = (from o in AppLanguages where o.ProjDomainDataSource.Data == "string" select o).FirstOrDefault();
             
                
                
                //cbo.SelectedItem = selectedLanguage;
                //ComboBoxItem comboitem = new ComboBoxItem();
                //comboitem.IsSelected = true;
                //comboitem.Content = "Test";

                //cbo.SelectedItem = comboitem;

    }

    still not set the first item..

    Innocent

    Wednesday, April 11, 2012 1:47 PM
  • I don't think your example has given the SelectItem a value anywhere.

    Wednesday, April 11, 2012 4:50 PM
  • How you want me to set the value ? in code behind or in xaml either is not working by the way I found this.

    http://blogs.msdn.com/b/kylemc/archive/2010/06/18/combobox-sample-for-ria-services.aspx#comments

    Thursday, April 12, 2012 3:21 PM
  • I don't use the RIA stuff because it seems too complex to me, and I think your problem MIGHT be that when the ItemsSource binding is done, there is nothing in the list yet.  And setting the SelectedItem at that point wouldn't do anything because the list is empty.

    So, assuming you can find someplace where any async call has been completed for the ItemsSource of the combobox, you could set SelectedItem there.

    Could be that blog post will help as it seems to be talking about async calls.

    Sorry, I don't know anything about RIA to be able to contribute.

    Thursday, April 12, 2012 4:43 PM
  • Thank you for sharing all your knowledge mtiede

    From the begining I have data in combobox list the only problem is I have to set the selecteditem. either in xaml or codebehind...

    data is directly coming through DDS+EF4 from entity in database( also I am fetching through RIA services which is basiclly a metadatafile and service file.)

    Once again thank you for everything.

    I still Not able to fixed the problem. Microsoft want many people to visit this silverlight blogs to see how much hardworking they are doing ....:)

    and guess what you still can't find the answer.

    combobox selected item = all headache

    Friday, April 13, 2012 5:06 PM
  • SL combobox and selecteditem work fine.  I use it a lot.  There is something about what your are doing that is causing the problem.

    Try making a new app from scratch.  Just create the list and selected item totally in code without any RIA or database involved.  Make sure you understand how that works first.  Then go back to your actual app and try to make it similar to what works.

    Make sure you implement INotifyPropertyChanged.

    Thursday, April 26, 2012 8:42 AM
  • Even If I create a new project for list and try there by using simple list and if it works,,,,,that will be great ,but as for now I need to set selected item based on RIA services. but not on simple list.

    My data is coming directly in combobox through binding Mode=bindingmode.twoway.

    what I try is :

    combobox.selectedindex =itemindex;  it works on local but not on production. 

     

     Thanks again mtiede@swtec..

     

    Thursday, April 26, 2012 4:14 PM
  • It's very difficult to say exactly what your issue is. I'm having trouble following your code and logic. But I can tell you this: What you want to do is possible. I just think you're going about it the wrong way.

    I think you should bind your selectedItem property rather than trying to set it in code behind.

    1) The combobox ItemsSource is one-way bound to your list of items.

    2) The combobox SelectedItem is two-way bound to a property that you need to create (we'll call it MySelectedItem) that is of the same type as the items in your list.

    I am not familiar with the domain data source, but I am familiar with RIA services, and I think some of the concepts should cross over.

    When you load your list of items that are used to populate the combo box through the DDS, there will be an event that is fired called LoadedData (http://msdn.microsoft.com/en-us/library/system.windows.controls.domaindatasource.loadeddata(v=vs.91).aspx).

    In this event, set your MySelectedProperty to whichever item you want to be selected from your List and it will be selected in the combobox, because your combobox SelectedITem is bound to that item.

     

    Thursday, April 26, 2012 7:18 PM
  • Josh,

       I think you meant MySelectedItem in the last paragraph instead of MySelectedProperty (in order to agree with the name you mentioned earlier).

    Friday, April 27, 2012 8:39 AM
  • You should make sure the ItemsSource is set first before selecting the SelectedValue. 

    More conveniently, is to use Kyle McClennan's [MSFT] ComboBox DataSource and set 

    <ComboBox  ... ... ex:Mode="Async" />

    This is the best way, and should have been part of Silverlight release. People have had so much trouble with ComboBoxes because this doesn't exist by default.

    Friday, April 27, 2012 9:59 AM
  • I wouldn't switch to another combobox type.  Most likely it will just replace one set of problems with another.  The provided ComboBox DOES work.

    I was looking back at the code and had a couple of questions.  Is LanguageList a single language?  Since you are saying List<LanguageList>, it makes it look like LanguageList is a single language.  If it isn't, that could be a source of problems.

    And, fwiw, I would make a Viewmodel.  The Viewmodel would have a property with notification for both the List and the SelectedItem.  Then in a Page I would make the datacontext of the page be an instance of that Viewmodel.  Then the View can have the combobox bindings to the List and the SelectedItem properties.  And everything should happen automatically because of the bindings and notification. 

    Sunday, April 29, 2012 7:26 AM
  • Here's an example.  It is written in Embarcadero Prism language, but C# is similar, but more complicated.

    Here is the MainPage.xaml:

    <UserControl
       
       x:Class="MvvmBase8.Pages.MainPage" 
       
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       
       xmlns:viewmodels="clr-namespace:MvvmBase8.Viewmodels"
       xmlns:views="clr-namespace:MvvmBase8.Views"
       >
       
       <UserControl.DataContext>
          <viewmodels:MainViewmodel/>
       </UserControl.DataContext>
    
       <views:MainView/>
       
    </UserControl>
    

    Note how it instantiates the Viewmodel and the View and "hooks them up" through the DataContext.

    Here is the MainView.xaml:

    <UserControl 
       
       x:Class="MvvmBase8.Views.MainView"
       
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       
       Width="400" 
       Height="300" 
       >
       <Grid x:Name="LayoutRoot">
    
          <Grid.RowDefinitions>
             <RowDefinition Height="Auto"/>
             <RowDefinition Height="Auto"/>
             <RowDefinition Height="Auto"/>
             <RowDefinition Height="Auto"/>
          </Grid.RowDefinitions>
    
          <TextBlock Text="Main View"/>
          <ComboBox 
             Grid.Row="1" 
             ItemsSource="{Binding LanguageList}"
             SelectedItem="{Binding SelectedLanguage, Mode=TwoWay}"
             DisplayMemberPath="Name"
             />
          <TextBlock Text="{Binding SelectedLanguage.Name}" Grid.Row="2"/>
          <TextBlock Text="{Binding SelectedLanguage.Code}" Grid.Row="3"/>
       </Grid>
    </UserControl>
    

    It expects the Viewmodel to have LanguageList and SelectedLanguage.

    Here is the MainViewmodel which instantiates the list and sets a default value for SelectedLanguage.  It also establishes the two properties and NOTIFICATION (which is the "notify" directive in the Prism language and has to be an implementation of INotifyPropertyChanges in C#).

    namespace MvvmBase8.Viewmodels;
    
    interface
    
       uses
          System.Collections.Generic;
    
       type
          Language = public class
             public
                property Name : String; notify;
                property Code : String; notify;
             end;
    
          MainViewmodel = public class
             public
                property LanguageList     : List<Language>; notify;
                property SelectedLanguage : Language;       notify;
                constructor;
             end;
    
    implementation
    
       constructor MainViewmodel;
          begin
          var temp := new List<Language>;
          temp.Add( new Language( Name:='US English',      Code:='en-US' ) );
          temp.Add( new Language( Name:='British English', Code:='en-BR' ) );
          temp.Add( new Language( Name:='French',          Code:='fr-FR' ) );
    
          LanguageList     := temp;
          SelectedLanguage := temp[0];
          end;
    
    end.
    

    Note that I only set LanguageList AFTER it is populated with the languages.  Otherwise, the binding will not see a "property change" of the list address after the languages are added to the list.  And then the selecteditem is just set to the first item in the list (which assumes there is at least one).

    Also note that there is no xaml code-behind code required.

    Hope that helps even if it isn't using RIA or any data access.  But the setup of the Viewmodel, View and Page should be similar.

    Sunday, April 29, 2012 10:01 AM
  •  <ComboBox x:Name="FruitscomboBox" Height="23" Margin="10,6,5,0" HorizontalAlignment="Stretch"
                                   VerticalAlignment="Top" Grid.Column="1" Grid.Row="2"
                              ItemsSource="{Binding TableNames,ElementName=DomainDataSource}"
                              SelectedItem="{Binding ColumnName,Mode=TwoWay}"
                             Loaded="FruitscomboBox_Loaded" IsEnabled="True" />


      private void FruitscomboBox_Loaded(object sender, RoutedEventArgs e)
            {
                Binding itemsSource = new Binding("TableNames") { Source = this.purchaseDomainDataSource.DomainContext};
                Binding SelectedItem = new Binding("TableName");//{ Mode = BindingMode.TwoWay };//ItemsSource="{Binding Source=TableName.ColumnName, Path=Data}"
                FruitscomboBox.SetBinding(ComboBox.ItemsSourceProperty, itemsSource);
                FruitscomboBox.DisplayMemberPath = "ColumnName"; 
               FruitscomboBox.SelectedItem = "Apple";
            }

     

    Can you correct me what's wrong in this above code.

    Friday, May 11, 2012 5:28 PM
  •  

    This is my xaml and code behind as follows:

     <ComboBox x:Name="FruitscomboBox" Height="23" Margin="10,6,5,0" HorizontalAlignment="Stretch"
                                   VerticalAlignment="Top" Grid.Column="1" Grid.Row="2"
                              ItemsSource="{Binding TableNames,ElementName=DomainDataSource}"
                              SelectedItem="{Binding ColumnName,Mode=TwoWay}"
                             Loaded="FruitscomboBox_Loaded" IsEnabled="True" />


      private void FruitscomboBox_Loaded(object sender, RoutedEventArgs e)
            {
                Binding itemsSource = new Binding("TableNames") { Source = this.DomainDataSource.DomainContext};
                Binding SelectedItem = new Binding("TableName");//{ Mode = BindingMode.TwoWay };//ItemsSource="{Binding Source=TableName.ColumnName, Path=Data}"
                FruitscomboBox.SetBinding(ComboBox.ItemsSourceProperty, itemsSource);
                FruitscomboBox.DisplayMemberPath = "ColumnName"; 
               FruitscomboBox.SelectedItem = "Apple";
            }

     

    Can you correct what's wrong in this above code?

     

    Friday, May 11, 2012 5:29 PM
  • If at some point you are looping through your items to assign them to your ComboBox, you might be able to filter out the ComboBoxItem you want and set IsSelected=true;

    Friday, May 11, 2012 6:29 PM
  • azam50004,

       Try setting the SelectedItem before setting the DisplayMemberPath.

       Also, setting SelectedItem to a string constant implies that the ItemsSource is a list of Strings.  Is that true?

       OR is the TableNames some sort of other object class?  I don't know Ria, but I would guess it is some sort of String Entity and not a String.  If that is the case, they you need to find the Entity in the TableNames that has a String property that is "Apple" and assign THAT object to the SelectedItem.

    Saturday, May 12, 2012 8:23 AM
  • @mtiede@swtec...  setting SelectedItem to a string constant implies that the ItemsSource is a list of Strings.  Is that true?

    Yes ,it's true that I have list of strings in that column which I want to display in combobox.(data is coming just combobox appear as blank, user need to click and select then its working).

    TableNames is just a query at Servicefile. and TableName is an entity in DB.

    Ex: GetFruits is a query to fetch data from that table based on our choice complete table or particular columns

    and     Fruit is just an entity in Oracle DB

    Hope it make sense.

    Thank you once again for all your suggestions and help

     


    ================================================
    I refered to this article in my book

    http://books.google.com/books?id=KKQB9SDF0LAC&pg=PA258&lpg=PA258&dq=silverlight+5+business+application+combobox&source=bl&ots=fFsqZj2R1a&sig=XAL5hyYwin29K1jK8WZ7Ja-6zsk&hl=en&sa=X&ei=AoSxT_nQI-2d6AHou_3CBg&ved=0CGcQ6AEwBA#v=onepage&q&f=false


    and I try by setting the primary key of the entity to selectedvaluepath still no help.

     

     


    let me describe you the problem step by step.


    1) Fruit entity is there in Oracle DB

    What I have in Service query to fetch data from db is.

    [Query(IsDefault=true)]

    public IQueryable<Animal> GetAnimals()

    {

    return this.ObjectContext.Animals.Include("Fruit").Include("Employee");  \\Including other entities in query to use this query as in DDS.

    }

    ----------------------------------------------------------------------------------------------------------------------------------------
    [Query(IsDefault=true)]
    public IQueryable<Fruit> GetFruits()
    {
    return this.ObjectContext.Fruits.OrderBy(p=p.FruitName); \\ columnName to be displayed in combobox);

    }

     

    [Query(IsDefault=true)]
    public IQueryable<Animal> GetAnimals()
    {
    return this.ObjectContext.Animals.OrderBy(o=o.AnimalAge); \\ columnName to be displayed in combobox);

    }

     

    ***********************************************************************************************************

    combobox codebehind and xaml code.

     <ComboBox x:Name="FruitscomboBox" Height="23" Margin="10,6,5,0" HorizontalAlignment="Stretch"
                                   VerticalAlignment="Top" Grid.Column="1" Grid.Row="2"
                              ItemsSource="{Binding Entities,ElementName=DomainDataSource}"
                              SelectedItem="{Binding ColumnName,Mode=TwoWay}"
                             Loaded="FruitscomboBox_Loaded" IsEnabled="True" />

     

      private void FruitscomboBox_Loaded(object sender, RoutedEventArgs e)
            {
                Binding itemsSource = new Binding("Entities") { Source = this.DomainDataSource.DomainContext};
                Binding SelectedItem = new Binding("Apple");
                FruitscomboBox.SetBinding(ComboBox.ItemsSourceProperty, itemsSource);
                FruitscomboBox.DisplayMemberPath = "ColumnName";
              
            }


    I again Try as follows:

    Binding SelectedItem = new Binding("Apple"); //before displaymemberPath, apple is one of the item from list of strings of dynamic data coming through RIA service but resulting an exception.
    (Catastrophic failure(exception from HRResult: 0x8000FFFF(E_UNEXPECTED))

    May be I am missing some thing really simple.

    Just want to confirm that I need to use combobox_Loaded event right? for Binding,Seletecitem,Itemssource

     

     

    Monday, May 14, 2012 5:56 PM
  •  

    @bugeyed

    No I am not looping anything, and I can't able to set in Xaml/codebehind IsSelected=true I think it doesn't have any property like IsSelected. it had IsEnabled which I already set as true.

     

    Thank you.

    Monday, May 14, 2012 6:04 PM
  • Azam-

    You do not bind the SelectedItem to a column, you bind it to an ENTITY, and in this case it needs to be an entity that is contained within the data that is loaded into the DomainDataSource control. This should be accessed through the DomainDataSource.DataView.CurrentItem property.

     <ComboBox x:Name="FruitscomboBox" Height="23" Margin="10,6,5,0" HorizontalAlignment="Stretch"
                                   VerticalAlignment="Top" Grid.Column="1" Grid.Row="2"
                              ItemsSource="{Binding TableNames,ElementName=DomainDataSource}"
                              SelectedItem="{Binding ColumnName,Mode=TwoWay}"
                             Loaded="FruitscomboBox_Loaded" IsEnabled="True" />

    That will NOT work. Instead you need to bind the SelectedItem to the CurrentItem of the DomainDataSource. I've never used the DomainDataSource myself, but I beleive it's something like this:

     <ComboBox x:Name="FruitscomboBox" Height="23" Margin="10,6,5,0" HorizontalAlignment="Stretch"
                                   VerticalAlignment="Top" Grid.Column="1" Grid.Row="2"
                              ItemsSource="{Binding TableNames,ElementName=DomainDataSource}"
                              SelectedItem="{Binding DataView.CurrentItem, ElementName=DomainDataSource, Mode=TwoWay}"
                              Loaded="FruitscomboBox_Loaded"
                              DisplayPath="NameOfFieldYouWantToBeDisplayed"
                              ValuePath ="NameOfFieldYouWantToUseAsTheValue" />

    What you are binding to here is the DataView.CurrentItem of your DomainDataSource. To control what field is displayed in the ComboBox, set the DisplayPath property. To Control what field is used as the value of the selected item, use the ValuePath property.

    If I could recommend something, it would be to not use the DomainDataSource except for simple purposes. I would not use it in a production application that customers would use. It would be better in my opinion to use a MVVM type approach where you at least use a ViewModel (Just a class that you write that implements INotifyPropertyChanged and loads the data and exposes it so that the UI can bind to it) instead of a DomainDataSource. This will give you more control over how it all works, and will be a lot more straight forward to implement advanced funcitonality if you need it.

    Monday, May 14, 2012 6:55 PM
  • I'm not sure a "Loaded" or "ValuePath"  are needed either.  I never use either of those.  But maybe it is something RIA needs.

    Tuesday, May 15, 2012 11:16 AM
  • JoshSommers ,

    It looks like your answers is very close  but when I set

    DisplayMemberPath ="DataTableColumnName" and SelectedValuePath="Value ex: Apple" its throwing an exception.Error 2 Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED)) ,

    I wish I could use INotify to rectify this but I have no idea how it works in MVVM approach.

    Basically data is coming in combobox but appear as blank, no selected value its displaying.

    after reading about INotify I went to this blog -> http://stackoverflow.com/questions/2910596/combobox-inotifypropertychanged-event-not-raised

    I wondered what to write in xaml and in codebehind for my combobox.

    I will really appreciate if you could post some code to go for MVVM approach. and I have EF4 ,SL5,Oracle,.Net4

    so that I can create a seperate class for my column which I have to bind to my combobox.

     

    Fruit entity - had many columns (I just have to display one column from this entity in annoying combobox)

     

    Thank you so much.

     

     

     

     

    Tuesday, May 15, 2012 3:32 PM
  • Ok, there is still some misunderstanding. Providing a full MVVM example is too much for me to do at the moment as I am very busy with my project, but there are a lot of resources out there for learning to do this when you are ready to take that step. But for now, you CAN get this to work with your domaindatasource.

    First, let's try to fully understand these two properties:

    1) DisplayMemberPath: This property controls what is DISPLAYED in the combobox, both in the dropdown and in the text area of the combobox. This property should contain the NAME of a field in your table. For example, say you have a field called "sName" in your table. Then you would set DisplayMemberPath="sName". This will cause the VALUE in that FIELD to be displayed in the combo box and in the dropdown.

    2) ValueMemberPath: This property should contain the NAME of a field in your table that you want to represent the VALUE, and will control what is returned in the codebehind or binding for the SelectedValue property. For example, say you have a GUID column called "ID". If you set the ValueMemberPath="ID" then in code behind when you get SelectedValue, you will get the ID for the selected item. If you do not set this property, the selectedValue will return the same thing as SelectedItem: the entity itself (not a value of a property on the entity, but the entity itself).

    I just want to make sure you understand that you should not put a hard-coded value in either of these properties (for example DO NOT set "apple" as the value for either of these properties, that is not how it works), they BOTH should contain the NAME of a FIELD.

    Tuesday, May 15, 2012 3:43 PM
  • Your biggest mistake is to use DomainDataSource as the ItemsSource of a combobox. It only works in rarest of cases. Most of the time, you'll find the odd misbehavior. This is because of a bug in combobox. You must assign the ItemsSource before assigning myComboBox.SelectedValue. I've been bitten by this before, and the only solution is to avoid it.

    The reason your code works in local but not in production is due to timing. The Production server takes a little longer to return the ItemsSource, but SelectedValue has already been set. 

    Use Kyle McClennan's [MSFT] ComboBox DataSource, and ComboBox.Mode="async" and it should work:

      <ComboBox Name="AComboBox" 
                ItemsSource="{Binding Data, ElementName=ASource}" 
                SelectedItem="{Binding A, Mode=TwoWay}" 
                ex:ComboBox.Mode="Async" />

    It works by helpinh ComboBox retain its selectedValue when ItemsSource is finally set.

    Tuesday, May 15, 2012 6:08 PM
  • In order to set combobox to Async mode, I need to add that dll file to consume in my project.  will you recommend to add that dll just to set the selected item so that combobox shouldn't appear blank.

     and I think I already try that. but I will try again and get back.

    Use Kyle McClennan's [MSFT] ComboBox DataSource, and ComboBox.Mode="async" and it should work:

    this blog is for SL4 but not SL5 , I am using SL5

    looks like @Joshsommer is correct I will follow your solution josh.(I believe that it has nothing to do with DDS)

    I am trying this comobbox thing from last one month only to set the selected item =some value. :)

    Thank you very much.

     

    Tuesday, May 15, 2012 6:26 PM
  • I don't think he is facing that issue. I have faced the bug you are speaking of before, it has nothing to do with using the DomainDataSource, it happens in any binding scenario when binding to the SelectedValue and possibly the SelectedIndex property. But I do not think it happens when binding to the SelectedItem property, and I also think that the bug you are referring to was resolved in SL5. Please correct me if you know this to be incorrect.

    Tuesday, May 15, 2012 6:32 PM
  • Azam:

    Did you try my previous suggestions?

    Do you understand what DisplayMemberPath and ValueMemberPath properties are user for now?

    I do not advise you getting sidetracked by this other combobox. You can make the normal combobox work if you set it up correctly, which so far, you have not.

     

    Tuesday, May 15, 2012 6:35 PM
  • @Josh, sorry I just got distracted by DDS and other answers.

    I am able to understand what you are saying, from beginning I have DisplayMemberPath = "Field"; (Field is one column of DB table)

    I don't have ValueMemberPath here in SL5 how to get that?

    Tuesday, May 15, 2012 7:06 PM
  • NO!!!!!!

    But I am sorry, I DID use the wrong property name.

    SelectedValuePath (Sorry, not ValueMemberPath) is the VALUE. http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selectedvaluepath(v=vs.95).aspx

    DisplayMemberPath is what is DISPLAYED. http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.displaymemberpath(v=vs.95).aspx

     

     

     

    Tuesday, May 15, 2012 7:13 PM
  • Thank you for quick response Josh,

    ok I understood, looks like problem lie in SelectedValuePath....Let me check that.

     <ComboBox x:Name="FruitComboBox" Height="23" Margin="10,6,5,0" HorizontalAlignment="Stretch"
                                   VerticalAlignment="Top" Grid.Column="1" Grid.Row="2"
                                  SelectedValuePath = "PrimaryKeyColumn"
                        Loaded="FruitComboBox_Loaded" SelectionChanged="FruitComboBox_SelectionChanged" IsEnabled="True" />

     

    CodeBehind modiefied as follows:

    Binding itemsSource = new Binding("Entities") { Source = this.DomainDataSource.DomainContext};
                Binding SelectedItem = new Binding("Entity"){ Mode = BindingMode.TwoWay };
                FruitcomboBox.SetBinding(ComboBox.ItemsSourceProperty, itemsSource);
                FruitcomboBox.DisplayMemberPath = "Field";//(column of db table which is a list of strings)";

    FruitCombobox.SelectedValuePath="Primarykeycolumn";

    Not fix.

    Tuesday, May 15, 2012 7:30 PM
  • You can technically not set either of those properties. The important property to set for you right now is the binding on the SelectedItem property. First just make sure that that is working, then set the other properties.

    If you do not set the displaymemberpath, the combobox will display the .ToString value of your entity, which usually resolves to the primary key, which in my case is always a GUID.

    If you do not set the SelectedValuePath property, then nothing will change with display, only what you get when you try to access the SelectedValue property. If the SelectedValuePath property is not set, then the SelectedValue property will return the full entity instead of a property on the entity.

    I suggest that at first you do not set either of these properties, and just get the bindings to work first. Then set the DisplayMemberPath property and confirm that it still works. Then, if and only if you NEED to set the SelectedValueMember property, you can set that property.

    Tuesday, May 15, 2012 7:42 PM
  • we are on the same track @Josh,You are 100% right,I just check that If I do not set DisplayMemberPath="column"; then Its taking my PrimarykeyValues and displaying in combobox but even combobox appear as blank initially , I have to click it to check wheather it has data in it.

    I am 100% sure about the DisplayMemberPath and binding now. that I set correctly to a database table column [example table : emp{ empId,empage,empname etc} I set as

    combobox.DisplaymemberPath="empname";

    and Binding SelectedItem=new Binding("empId"){Mode=BindingMode.TwoWay};

     From here onward I will set everything in codebehind.

     

     

     

     

     

     

     

    Tuesday, May 15, 2012 7:59 PM
  • No buddy, you've still got it wrong. Cry

    Go back a few posts and look again at what I said about binding the SelectedItem. You need to bind this to the selected item of the DomainDataSource. You need to specify WHICH ENTITY TO BIND TO, NOT WHICH FIELD.

    Please look at this again:

    <ComboBox
    x:Name="FruitscomboBox" 
    ItemsSource="{Binding TableName, ElementName=YouDomainDataSourceName}"
    SelectedItem="{Binding DataView.CurrentItem, ElementName=YourDomainDataSourceName, Mode=TwoWay}"
     />

    DomainDataSource.DataView.CurrentItem: http://msdn.microsoft.com/en-us/library/system.windows.controls.domaindatasourceview.currentitem(v=vs.91).aspx

    Tuesday, May 15, 2012 8:08 PM
  • I am sorry, I want to inform you that I remove selected item, Itemsource from XAML I just have the below exactly same code in xaml and in codebehind,I want to do everything in codebehind to avoid confusion.

    <combobox x:Name="FruitCombobox" Height="23" Margin="10,6,5,0" HorizontalAlignment="Stretch"
                                   VerticalAlignment="Top" Grid.Column="1" Grid.Row="2" Loaded="FruitcomboBox_Loaded" SelectionChanged="FruitcomboBox_SelectionChanged" IsEnabled="True" />

    Exact Code Behind:

    Binding itemsSource = new Binding("Entities") { Source = this.DomainDataSource.DomainContext};
                Binding SelectedItem = new Binding("EntityUID"){ Mode = BindingMode.TwoWay };
                FruitcomboBox.SetBinding(ComboBox.ItemsSourceProperty, itemsSource);

     FruitcomboBox.SetBinding(ComboBox.SelectedItemProperty, SelectedItem);

                FruitcomboBox.DisplayMemberPath = "Field";//(column of db table which is a list of strings)";

    Tuesday, May 15, 2012 8:15 PM
  • This is actual XAML from a sample project I just created. You still need to fill in the DomainDataSource properties to load the data, etc, but this is how the bindings should be setup:

            <riaControls:DomainDataSource Name="DomainDataSource1" />
            <ComboBox 
    DisplayMemberPath="FieldNameToDisplay"
    SelectedValuePath="FieldNameToUseAsValue"
    ItemsSource="{Binding ElementName=DomainDataSource1, Path=DataView}"
    SelectedItem="{Binding Path=DataView.CurrentItem, Mode=TwoWay, ElementName=DomainDataSource1}" />
    Tuesday, May 15, 2012 8:20 PM
  • You're not avoiding any confusion, you're creating more confusion. Try to follow the instructions and once you have it working, then you can change it and try to do things your way. Setting up the bindings in the code behind can be ok if you know what you are doing, but it can be disasterous if you do not.

    Tuesday, May 15, 2012 8:22 PM
  • I remove the loaded event and set everything exactly as you mention in xaml. (so now I don't have codebehind for combobox)

    but I am not getting any data in combobox due to combobox.setbinding I can't do in xaml.

    need to fill the combobx.

    You hv done alot for this problem today, Can you please post code just for codebehind. so that I can set all the properties in codebehind.

    Tuesday, May 15, 2012 8:37 PM
  • Look, you're not really getting it my friend. I can only provide you with an example. You need to be smart enouogh to know which pieces you need to change to fit within your code, I can't really help you with that.

    I think you'd better step away from this and do some reading. Look at other examples of how to use binding. You clearly do not understand how it works so you need to start by learning, then move on to "doing".

    You do NOT need to do ANYTHING in code behind to get the bindings to work. You can do it all in the XAML, and my example shows you exactly how to do that, but you need to fill in the correct names of your fields.

    If yuo want to paste your XAML here I will try to look at it and fix it for you, but that is the last thing I can offer at this point. I strongly advise you to take some time to read a book on Silverlight that includes a section on Binding. I recommend Business Applications with Silverlight by Anderson.

    Tuesday, May 15, 2012 8:43 PM
  • 1. if you use combobox as a standalone control, you can set selecteditem, selectedvalue, selectedindex. They all worked.

    2. if you use databinding, use code behind to changed the property/value which binds to the selectedvaluepath. It will work. (well at least it worked for me :) )

    Tuesday, May 15, 2012 8:43 PM
  • Not helpful.

    He is not binding to the SelectedValue, so this is irrellevant and just adding to the confusion.

    Tuesday, May 15, 2012 8:49 PM
  • I have Pro Business Application with SL5 by Chris Anderson/SL4 in action by Pete Brown both the books right beside me. Yes you are right that May be I need to read a little.

    Anyhow Here is my code goes for xaml.


    <riaControls:DomainDataSource Name=DomainDataSource1 AutoLoad="True" QueryName ="GetFruitsQuery" />

     <ComboBox x:Name="FruitcomboBox" Height="23" Margin="10,6,5,0" HorizontalAlignment="Stretch"
                                   VerticalAlignment="Top" Grid.Column="1" Grid.Row="2"
                              DisplayMemberPath="ColumnName" SelectedValuePath="FruitUID"(primarykeycolumnName)
                              ItemsSource="{Binding Source/ElementNamepath=DomainDataSource1,Path=DataView}" //(I try with both source and ElementName}
                              SelectedItem="{BindingPath=DataView.CurrentItem,Mode=TwoWay,ElementName=DomainDataSource1}"
                           IsEnabled="True" />

     

    Thank you for everything.

    Tuesday, May 15, 2012 8:57 PM
  • Normally, the attributes that are set in xaml are not order dependent. But you are asking for trouble on a combobox to set them in the order you are setting them.  (I know at least in some previous SL versions they didn't work right.  Haven't tried in SL 5)

    So, if it doesn't know the ItemsSource and it doesn't know the SelectedItem, how could it know what to display?  That might be a problem by ordering your parameters the way you have.

    I would recommend:

    1. ItemsSource

    2. SelectedItem

    3. DisplayMemberPath

    4. SelectedValuePath

    And maybe it works just fine now since Josh has them in a different order.  I'm just making the suggestion that you put them in this order as I know it worked in the past.

    Wednesday, May 16, 2012 3:18 AM
  • Azam,

    Can you please paste in your actual XAML without changing anything? It's hard for me to help when there are parts that are not your actual code. PLease just put here your actual xaml without any notes or substitutions.

    Wednesday, May 16, 2012 12:41 PM
  • I am sorry for the late reply, Josh I can't post the exact code here, we fixed the problem by selecting a row which by default select an Item in combobox for me, If we select some row in Datagrid that row value will be reflected in combobox.

    but I am still interested in fixing, I try to use kyle blog .dll in my project and use Mode=Async & AsyncEager

    When I download sample project I found that he define seperate DataSource just for combobox.

    http://blogs.msdn.com/b/kylemc/archive/2010/06/18/combobox-sample-for-ria-services.aspx

    mtiede@swtec... I try to follow your recommdn : as

    Itemsource

    SelectedItem

    DisplayMemberPath

    SelectedValuePath

    but no help.

     

    And Finally I am trying this ->

     InitializeComponent();

    {            ComboBox comboo = new ComboBox { DisplayMemberPath = "PhaseName" };
                Binding SelectedValuePath = new Binding("PhaseUID");

                Binding itemsSource = new Binding("Phases") { Source = this.phaseDomainDataSource.DomainContext };
                comboo.SetBinding(ComboBox.ItemsSourceProperty, itemsSource);

                Binding selectedItem = new Binding("PhaseUID") { Mode = BindingMode.TwoWay };
                comboo.SetBinding(ComboBox.SelectedItemProperty, selectedItem);


                //comboo.HorizontalAlignment = HorizontalAlignment.Stretch;
                comboo.VerticalAlignment = VerticalAlignment.Top;
                comboo.Height = 25;
                comboo.Width = 270;
                comboo.Margin = new Thickness(10, 6, 5, 0);

                LayoutRoot.Children.Add(comboo);

    and again data is coming but selected item is not working.

    }

    Josh which version are you using SL5 ?

    Thank you Josh & metde@ once again for all your comments and suggesitons.

    Thursday, May 17, 2012 6:45 PM