Solved

WPF DataGrid using 2 DataGridComboBoxColumns and reloading the second ComboBox when the first one changes.

Posted on 2010-09-01
3
1,494 Views
Last Modified: 2012-05-10

Open in new window


Open in new window

Hi guys,  I would like to know how to link 2 data bound DataGridComboBox columns in WPF such that when the first combo box value changes the second one is reloaded based upon a filter or selection from the first combo box.  

I have the DataGrid and DataGridComboBoxColumn's pretty much working correctly except for this particular problem.

There is a master – detail relationship between Event Type and Competition such that when the Event Type changes the Competitions combo box needs to be reloaded.  Please see the table definitions below:

CREATE TABLE [dbo].[EventTypes](
      [EventTypeID] [int] IDENTITY(1,1) NOT NULL,
      [Name] [nvarchar](255) NOT NULL,
 CONSTRAINT [PK_EventTypeID] PRIMARY KEY CLUSTERED
(
      [EventTypeID] ASC
)
GO

CREATE TABLE [dbo].[Competitions](
      [CompetitionID] [int] IDENTITY(1,1) NOT NULL,
      [EventTypeID] [int] NOT NULL,
      [Name] [nvarchar](255) NOT NULL,
 CONSTRAINT [PK_CompetitionID] PRIMARY KEY CLUSTERED
(
      [CompetitionID] ASC
)

GO

ALTER TABLE [dbo].[Competitions]  WITH CHECK ADD  CONSTRAINT [FK_Competitions_EventTypes] FOREIGN KEY([EventTypeID])
REFERENCES [dbo].[EventTypes] ([EventTypeID])
GO

ALTER TABLE [dbo].[Competitions] CHECK CONSTRAINT [FK_Competitions_EventTypes]
GO


Find enclosed samples of my code (I have removed many irrelevant columns from the grid for clarity)… I am using .NET 4.0 with VS 2010 and C#.

// Extract from Main.xaml

<DataGrid x:Name="datagridBetsPlaced" DataContext="{StaticResource usp_BetsPlaced_SelectForUserAccountIDViewSource}" AutoGenerateColumns="False" EnableRowVirtualization="True"
HorizontalAlignment="Stretch" ItemsSource="{Binding}"
            RowDetailsVisibilityMode="VisibleWhenSelected" VerticalAlignment="Stretch"
            AlternatingRowBackground="Aqua" CanUserAddRows="False" Margin="0,1,0,-1">

    <DataGrid.Resources>
        <ObjectDataProvider x:Key="eventTypesDataProvider" ObjectType="{x:Type my:Database}" MethodName="GetEventTypes"/>
        <ObjectDataProvider x:Key="competitionsDataProvider" ObjectType="{x:Type my:Database}" MethodName="GetCompetitions"/>
    </DataGrid.Resources>

    <DataGrid.Columns>
        <DataGridTextColumn x:Name="betIDColumn" Binding="{Binding Path=BetID}" Header="Bet ID" IsReadOnly="True" Width="SizeToHeader" Visibility="Hidden" />
        <DataGridComboBoxColumn x:Name="eventTypeIDColumn" Width="150" Visibility="Visible"
            SelectedValueBinding="{Binding EventTypeID}"
            ItemsSource="{Binding Source={StaticResource eventTypesDataProvider}}"
            SelectedValuePath="ItemData"
            DisplayMemberPath="Text"
            Header="Event Type"
        />
        <DataGridComboBoxColumn x:Name="competitionIDColumn" Width="150" Visibility="Visible"
            SelectedValueBinding="{Binding CompetitionID}"
            ItemsSource="{Binding Source={StaticResource competitionsDataProvider}}"
            SelectedValuePath="ItemData"
            DisplayMemberPath="Text"
            Header="Competition"
        />
        <DataGridTextColumn x:Name="decimalOddsColumn" Binding="{Binding Path=DecimalOdds}" Header="Decimal Odds" Width="100" />
        <DataGridTextColumn x:Name="stakeColumn" Binding="{Binding Path=Stake}" Header="Stake" Width="75" />
        <DataGridTextColumn x:Name="actualReturnColumn" Binding="{Binding Path=ActualReturn}" Header="Actual Return" Width="100" />
    </DataGrid.Columns>
</DataGrid>


// Extract from Database class

public static class Database
{
  public static List<ListComboData> GetEventTypes()
  {
      return LoadEventTypesList(Database.LanguageID);
  }

  // I need to pass an EventTypeID parameter into here which is based upon the SelectedValue in the Event Type DataGridComboBoxColumn
  public static List<ListComboData> GetCompetitions(int EventTypeID)
  {
      return LoadCompetitionsListForEventTypeID(EventTypeID);
  }

        private static List<ListComboData> LoadEventTypesList()
        {

            List<ListComboData> ListData = new List<ListComboData>();

            try
            {
                SqlCommand thisCommand = Connection.CreateCommand();
                thisCommand.CommandType = CommandType.StoredProcedure;
                thisCommand.CommandText = "dbo.usp_EventTypes_SelectForList";

                SqlDataReader reader = thisCommand.ExecuteReader();

                while (reader.Read())
                {
                    ListData.Add(new ListComboData(reader["Name"].ToString(), (int)reader["EventTypeID"]));
                }

                reader.Close();

            }
            catch (SqlException e)
            {
                MessageBox.Show(e.Message);
            }

            return ListData;
        }

        private static List<ListComboData> LoadCompetitionsListForEventTypeID(int EventTypeID)
        {

            List<ListComboData> ListData = new List<ListComboData>();

            try
            {
                SqlCommand thisCommand = Connection.CreateCommand();
                thisCommand.CommandType = CommandType.StoredProcedure;
                thisCommand.CommandText = "dbo.usp_Competitions_SelectForListByEventTypeID";

                SqlParameter paramEventTypeID = thisCommand.Parameters.Add("@EventTypeID", SqlDbType.Int);
                paramEventTypeID.Direction = ParameterDirection.Input;

                paramLanguageID.Value = LanguageID;
                paramEventTypeID.Value = EventTypeID;

                SqlDataReader reader = thisCommand.ExecuteReader();

                while (reader.Read())
                {
                    ListData.Add(new ListComboData(reader["Name"].ToString(), (int)reader["CompetitionID"]));
                }

                reader.Close();
            }
            catch (SqlException e)
            {
                MessageBox.Show(e.Message);
            }

            return ListData;
        }

}


0
Comment
Question by:jboydell
  • 3
3 Comments
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 33653051
a sample which implements this functionality. two combo's filled by country and counties. On change of country the counties of that country is populated in the county combo.
0
 
LVL 29

Accepted Solution

by:
Gautham Janardhan earned 500 total points
ID: 33653055
Converters, Country and Counties
public class HCRCountry
    {
        public string CountryName { get; set; }
        public int CountryID { get; set; }
        public List<HCRCountry> getCountryAll()
        {
            return new List<HCRCountry>()
            {
                new HCRCountry()
                {
                    CountryID = 1,
                    CountryName = "India1"
                },
                new HCRCountry()
                {
                    CountryID = 2,
                    CountryName = "India2"
                },
                new HCRCountry()
                {
                    CountryID = 3,
                    CountryName = "India3"
                },
                new HCRCountry()
                {
                    CountryID = 4,
                    CountryName = "India4"
                }
            };
        }
    }

    public class HCRCounty
    {
        public string CountyName { get; set; }
        public int CountyID { get; set; }
        public List<HCRCounty> getCountiesByCountry(int country)
        {
            return new List<HCRCounty>()
            {
                new HCRCounty()
                {
                    CountyName = "County for country" + country.ToString(),
                    CountyID = 1
                }
            };
        }

        public List<HCRCounty> getCountiesByCountry(object country)
        {
            return getCountiesByCountry((int)country);
        }
    }

    public class ConverterTemp : IMultiValueConverter, IValueConverter
    {
        #region IMultiValueConverter Members

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values != null && values.Length == 2 && (values[0] as HCRCountry) != null)
            {
                var temp = values[0] as HCRCountry;
                return temp.CountryID;
            }
            return 0;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            return new object[] { value, value };
        }

        #endregion

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }

        #endregion
    }

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 33653063
Xaml

also these lines in code behind

this.DataContext= this  -> put this in initialize component

and a property

public int CountryID { get; set; }
<Grid.Resources>
            <common:ConverterTemp x:Key="MultiConv" />
            <common:ConverterTemp x:Key="IDConv" />
            <ObjectDataProvider x:Key="Countries"
                            ObjectType="{x:Type common:HCRCountry}"
                            MethodName="getCountryAll" />
            <ObjectDataProvider x:Key="Counties"
                            ObjectType="{x:Type common:HCRCounty}"
                            MethodName="getCountiesByCountry">
                <ObjectDataProvider.MethodParameters>
                    <system:Int32>0</system:Int32>
                </ObjectDataProvider.MethodParameters>
            </ObjectDataProvider>
        </Grid.Resources>
        <StackPanel>
            <ComboBox Name="cboCountry"
                  Grid.Column="3"
                  Grid.Row="2"
                  Margin="5,2"
                  ItemsSource="{Binding Source={StaticResource Countries}}"
                  DisplayMemberPath="CountryName"
                  SelectedValuePath="CountryID">
                <ComboBox.SelectedValue>
                    <MultiBinding Converter="{StaticResource MultiConv}"  >
                        <Binding Path="CountryID" 
                                 Converter="{StaticResource IDConv}" 
                                 UpdateSourceTrigger="PropertyChanged" />
                        <Binding Source="{StaticResource Counties}"    
                                 Path="MethodParameters[0]"    
                                 BindsDirectlyToSource="True"
                                 Converter="{StaticResource IDConv}"
                                 Mode="OneWayToSource"/>
                    </MultiBinding>
                </ComboBox.SelectedValue>
            </ComboBox>
            
            <ComboBox Name="cboCounty"
                  ItemsSource="{Binding Source={StaticResource Counties}}"
                  DisplayMemberPath="CountyName"
                  SelectedValuePath="CountyID">
            </ComboBox>

        </StackPanel>

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
This is a video that shows how the OnPage alerts system integrates into ConnectWise, how a trigger is set, how a page is sent via the trigger, and how the SENT, DELIVERED, READ & REPLIED receipts get entered into the internal tab of the ConnectWise …

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now