private void ClearResults()
        {
            messagePanel.Visibility = System.Windows.Visibility.Collapsed;
            messagePanel.Text = string.Empty;
            descriptionPanel.PanelMode = Controls.GadgetDescriptionPanel.DescriptionPanelMode.Collapsed;

            foreach (Grid grid in StrataGridList)
            {
                grid.Children.Clear();
                grid.RowDefinitions.Clear();
            }

            foreach (Grid grid in strataChiSquareGridList)
            {
                grid.Children.Clear();
                grid.RowDefinitions.Clear();
            }

            foreach (TextBlock textBlock in gridDisclaimerList)
            {
                panelMain.Children.Remove(textBlock);
            }

            foreach (GadgetStrataListPanel strataPanel in strataListPanels)
            {
                strataPanel.RowClicked -= new StrataGridRowClickedHandler(strataListPanel_RowClicked);
                strataPanel.Clear();
            }

            strataGroupPanel = null;
            strataListPanels.Clear();
            StrataGridList.Clear();
            strataChiSquareGridList.Clear();
            strata2x2GridList.Clear();
            groupList.Clear();
            StrataExpanderList.Clear();

            panelMain.Children.Clear();
        }
        /// <summary>
        /// Closes the gadget
        /// </summary>
        protected override void CloseGadget()
        {
            if (worker != null && worker.WorkerSupportsCancellation)
            {
                worker.CancelAsync();
            }

            if (worker != null)
            {
                worker.DoWork -= new System.ComponentModel.DoWorkEventHandler(worker_DoWork);
                worker.RunWorkerCompleted -= new System.ComponentModel.RunWorkerCompletedEventHandler(worker_WorkerCompleted);
            }
            if (baseWorker != null)
            {
                baseWorker.DoWork -= new System.ComponentModel.DoWorkEventHandler(Execute);
            }

            this.GadgetStatusUpdate -= new GadgetStatusUpdateHandler(RequestUpdateStatusMessage);
            this.GadgetCheckForCancellation -= new GadgetCheckForCancellationHandler(IsCancelled);

            for (int i = 0; i < StrataGridList.Count; i++)
            {
                StrataGridList[i].Children.Clear();
            }
            this.StrataGridList.Clear();

            for (int i = 0; i < strataChiSquareGridList.Count; i++)
            {
                strataChiSquareGridList[i].Children.Clear();
            }

            foreach (GadgetMatchedPairPanel grid2x2 in this.strata2x2GridList)
            {
                grid2x2.Dispose();
                grid2x2.ValuesUpdated -= new TwoByTwoValuesUpdatedHandler(matchedPairPanel_ValuesUpdated);
            }

            foreach (GadgetStrataListPanel strataPanel in strataListPanels)
            {
                strataPanel.RowClicked -= new StrataGridRowClickedHandler(strataListPanel_RowClicked);
                strataPanel.Clear();
            }

            strataListPanels.Clear();
            strataGroupPanel = null;
            this.strataChiSquareGridList.Clear();
            this.strata2x2GridList.Clear();
            this.groupList.Clear();
            this.StrataExpanderList.Clear();
            this.panelMain.Children.Clear();

            base.CloseGadget();

            GadgetOptions = null;
        }
        private void AddFreqGrid(string strataVar, string value, string crosstabVar, string groupReference, DataTable table)
        {
            StackPanel crosstabPanel = new StackPanel();
            StackPanel groupPanel = new StackPanel();

            bool strataSummaryOnly = (bool)checkboxStrataSummaryOnly.IsChecked;
            bool isGrouped = this.DashboardHelper.GetAllGroupsAsList().Contains(GadgetOptions.MainVariableName);
            if (isGrouped && strataGroupPanel == null)
            {
                strataGroupPanel = new GadgetStrataListPanel(StrataListPanelMode.GroupMode);
                strataGroupPanel.SnapsToDevicePixels = true;
                panelMain.Children.Add(strataGroupPanel);
            }

            groupPanel.Tag = groupReference;
            bool inList = false;

            foreach (StackPanel panel in groupList)
            {
                if (panel.Tag == groupPanel.Tag)
                {
                    groupPanel = panel;
                    inList = true;
                }
            }

            if (!inList)
            {
                groupList.Add(groupPanel);
            }

            int columnCount = table.Columns.Count;

            Expander expander = new Expander();

            TextBlock txtExpanderHeader = new TextBlock();
            txtExpanderHeader.Text = value;
            txtExpanderHeader.Style = this.Resources["genericOutputExpanderText"] as Style;

            string formattedValue = value;

            if (string.IsNullOrEmpty(strataVar) && GadgetOptions.StrataVariableNames.Count == 0)
            {
                formattedValue = crosstabVar;
            }
            else
            {
                if (value.EndsWith(" = "))
                {
                    formattedValue = value + DashboardHelper.Config.Settings.RepresentationOfMissing;
                }
            }

            if (isGrouped)
            {
                formattedValue = groupReference + ", " + formattedValue;
            }

            txtExpanderHeader.Text = formattedValue;
            expander.Header = txtExpanderHeader;

            if (columnCount == 3 && table.Rows.Count == 2 && (isRunningGrouped2x2 == null || isRunningGrouped2x2 == true)) // is 2x2
            {
                isRunningGrouped2x2 = true;

                decimal yyVal = decimal.Parse(table.Rows[0][1].ToString());
                decimal ynVal = decimal.Parse(table.Rows[0][2].ToString());
                decimal nyVal = decimal.Parse(table.Rows[1][1].ToString());
                decimal nnVal = decimal.Parse(table.Rows[1][2].ToString());

                Controls.GadgetTwoByTwoPanel twoByTwoPanel = null;

                try
                {
                    twoByTwoPanel = new Controls.GadgetTwoByTwoPanel(yyVal, ynVal, nyVal, nnVal);
                }
                catch (DivideByZeroException ex)
                {
                    return;
                }

                twoByTwoPanel.ValuesUpdated += new TwoByTwoValuesUpdatedHandler(twoByTwoPanel_ValuesUpdated);

                if (checkboxHorizontal.IsChecked == true)
                {
                    twoByTwoPanel.Orientation = Orientation.Vertical;
                }
                else
                {
                    twoByTwoPanel.Orientation = Orientation.Horizontal;
                }

                twoByTwoPanel.Margin = new Thickness(5);

                if (isGrouped)
                {
                    twoByTwoPanel.ExposureVariable = groupReference;
                }
                else
                {
                    twoByTwoPanel.ExposureVariable = this.GadgetOptions.MainVariableName;
                    if (strataSummaryOnly)
                    {
                        twoByTwoPanel.Visibility = System.Windows.Visibility.Collapsed;
                        expander.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
                twoByTwoPanel.OutcomeVariable = this.GadgetOptions.CrosstabVariableName;

                twoByTwoPanel.OutcomeYesLabel = table.Columns[1].ColumnName;
                twoByTwoPanel.OutcomeNoLabel = table.Columns[2].ColumnName;

                twoByTwoPanel.ExposureYesLabel = table.Rows[0][0].ToString();
                twoByTwoPanel.ExposureNoLabel = table.Rows[1][0].ToString();

                if (YesValues != null && YesValues.Count > 0 && NoValues != null && NoValues.Count > 0)
                {
                    twoByTwoPanel.OutcomeYesLabel = Config.Settings.RepresentationOfYes;
                    twoByTwoPanel.OutcomeNoLabel = Config.Settings.RepresentationOfNo;

                    twoByTwoPanel.ExposureYesLabel = Config.Settings.RepresentationOfYes;
                    twoByTwoPanel.ExposureNoLabel = Config.Settings.RepresentationOfNo;
                }

                if (showPercents)
                {
                    twoByTwoPanel.ShowRowColumnPercents = true;
                }
                else
                {
                    twoByTwoPanel.ShowRowColumnPercents = false;
                }

                if (string.IsNullOrEmpty(strataVar) && GadgetOptions.StrataVariableNames.Count == 0)
                {
                    crosstabPanel.Margin = (Thickness)this.Resources["genericElementMargin"];
                    crosstabPanel.Children.Add(twoByTwoPanel);

                    if (isGrouped && strataGroupPanel != null)
                    {
                        StrataGridListRow sRow = new StrataGridListRow();
                        sRow.StrataLabel = groupReference;
                        sRow.OutcomeRateExposure = twoByTwoPanel.OutcomeRateExposure;
                        sRow.OutcomeRateNoExposure = twoByTwoPanel.OutcomeRateNoExposure;
                        sRow.RiskRatio = twoByTwoPanel.RiskRatio;
                        sRow.RiskLower = twoByTwoPanel.RiskRatioLower;
                        sRow.RiskUpper = twoByTwoPanel.RiskRatioUpper;
                        sRow.OddsRatio = twoByTwoPanel.OddsRatio;
                        sRow.OddsLower = twoByTwoPanel.OddsRatioLower;
                        sRow.OddsUpper = twoByTwoPanel.OddsRatioUpper;
                        strataGroupPanel.AddRow(sRow);
                        strataGroupPanel.RowClicked += new StrataGridRowClickedHandler(strataGroupPanel_NoStrata_RowClicked);
                        strataGroupPanel.ExpandAllClicked += new StrataGridExpandAllClickedHandler(strataGroupPanel_NoStrata_ExpandAllClicked);
                    }

                    groupPanel.Children.Add(crosstabPanel);
                    //panelMain.Children.Add(crosstabPanel);
                    if (!panelMain.Children.Contains(groupPanel))
                    {
                        panelMain.Children.Add(groupPanel);
                    }
                }
                else
                {
                    GadgetStrataListPanel strataListPanel = new GadgetStrataListPanel();

                    bool found = false;
                    foreach (UIElement element in groupPanel.Children)
                    {
                        if (element is GadgetStrataListPanel)
                        {
                            found = true;
                            strataListPanel = (element as GadgetStrataListPanel);
                            break;
                        }
                    }

                    if (!found)
                    {
                        strataListPanel.RowClicked += new StrataGridRowClickedHandler(strataListPanel_RowClicked);
                        strataListPanel.ExpandAllClicked += new StrataGridExpandAllClickedHandler(strataListPanel_ExpandAllClicked);
                        strataListPanel.SnapsToDevicePixels = true;
                        strataListPanels.Add(strataListPanel);
                        groupPanel.Children.Add(strataListPanel);

                        if (!isGrouped && strataSummaryOnly)
                        {
                            strataListPanel.Visibility = System.Windows.Visibility.Collapsed;
                        }
                        //panelMain.Children.Add(strataListPanel);
                    }

                    StrataGridListRow sRow = new StrataGridListRow();
                    sRow.StrataLabel = formattedValue;
                    sRow.OutcomeRateExposure = twoByTwoPanel.OutcomeRateExposure;
                    sRow.OutcomeRateNoExposure = twoByTwoPanel.OutcomeRateNoExposure;
                    sRow.RiskRatio = twoByTwoPanel.RiskRatio;
                    sRow.RiskLower = twoByTwoPanel.RiskRatioLower;
                    sRow.RiskUpper = twoByTwoPanel.RiskRatioUpper;
                    sRow.OddsRatio = twoByTwoPanel.OddsRatio;
                    sRow.OddsLower = twoByTwoPanel.OddsRatioLower;
                    sRow.OddsUpper = twoByTwoPanel.OddsRatioUpper;

                    strataListPanel.AddRow(sRow);
                    if (isGrouped && strataGroupPanel != null)
                    {
                        strataListPanel.ExpanderHeader = groupReference;
                        sRow = new StrataGridListRow();
                        sRow.StrataLabel = groupReference;
                        sRow.OutcomeRateExposure = null;
                        sRow.OutcomeRateNoExposure = null;
                        sRow.RiskRatio = null;
                        sRow.RiskLower = null;
                        sRow.RiskUpper = null;
                        sRow.OddsRatio = null;
                        sRow.OddsLower = null;
                        sRow.OddsUpper = null;
                        strataGroupPanel.AddRow(sRow);
                        strataGroupPanel.RowClicked += new StrataGridRowClickedHandler(strataGroupPanel_RowClicked);
                        strataGroupPanel.ExpandAllClicked += new StrataGridExpandAllClickedHandler(strataGroupPanel_ExpandAllClicked);
                    }

                    twoByTwoPanel.Tag = formattedValue;
                    crosstabPanel.Margin = (Thickness)this.Resources["genericElementMargin"];
                    crosstabPanel.Children.Add(twoByTwoPanel);
                    expander.Margin = (Thickness)this.Resources["expanderMargin"];
                    expander.IsExpanded = true;
                    expander.Content = crosstabPanel;
                    groupPanel.Children.Add(expander);
                    //panelMain.Children.Add(expander);
                    StrataExpanderList.Add(expander);

                    if (groupList.Count == 0)
                    {
                        groupList.Add(groupPanel);
                    }

                    if (!panelMain.Children.Contains(groupPanel))
                    {
                        panelMain.Children.Add(groupPanel);
                    }
                }

                strata2x2GridList.Add(twoByTwoPanel);

                return;
            }
            else if ((columnCount != 3 || table.Rows.Count != 2) && (isRunningGrouped2x2 == true))
            {
                return;
            }

            isRunningGrouped2x2 = false;

            Grid chiSquaregrid = new Grid();
            chiSquaregrid.Tag = value;

            chiSquaregrid.HorizontalAlignment = HorizontalAlignment.Center;
            chiSquaregrid.Margin = new Thickness(0, 5, 0, 10);
            chiSquaregrid.Visibility = System.Windows.Visibility.Collapsed;

            chiSquaregrid.ColumnDefinitions.Add(new ColumnDefinition());
            chiSquaregrid.ColumnDefinitions.Add(new ColumnDefinition());
            chiSquaregrid.ColumnDefinitions.Add(new ColumnDefinition());

            chiSquaregrid.RowDefinitions.Add(new RowDefinition());
            chiSquaregrid.RowDefinitions.Add(new RowDefinition());

            Grid grid = new Grid();
            grid.Tag = value;
            grid.Style = this.Resources["genericOutputGrid"] as Style;
            grid.Visibility = System.Windows.Visibility.Collapsed;
            grid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;

            for (int i = 0; i < columnCount; i++)
            {
                ColumnDefinition column = new ColumnDefinition();
                column.Width = GridLength.Auto;
                grid.ColumnDefinitions.Add(column);
            }

            ColumnDefinition totalColumn = new ColumnDefinition();
            totalColumn.Width = GridLength.Auto;
            grid.ColumnDefinitions.Add(totalColumn);

            ScrollViewer sv = new ScrollViewer();
            sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
            sv.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            sv.MaxHeight = System.Windows.SystemParameters.PrimaryScreenHeight - 320;
            sv.MaxWidth = System.Windows.SystemParameters.PrimaryScreenWidth - 300;
            sv.Margin = (Thickness)this.Resources["expanderMargin"];

            Grid gridOuter = new Grid();
            gridOuter.ColumnDefinitions.Add(new ColumnDefinition());
            gridOuter.ColumnDefinitions.Add(new ColumnDefinition());
            gridOuter.RowDefinitions.Add(new RowDefinition());
            gridOuter.RowDefinitions.Add(new RowDefinition());

            Grid.SetColumn(grid, 1);
            Grid.SetRow(grid, 1);
            gridOuter.Children.Add(grid);

            Canvas exposureCanvas = new Canvas();
            Grid.SetColumn(exposureCanvas, 0);
            Grid.SetRow(exposureCanvas, 1);

            exposureCanvas.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            exposureCanvas.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            exposureCanvas.Width = 25;
            Binding canvasHeightBinding = new Binding("Height");
            canvasHeightBinding.Source = grid;
            exposureCanvas.SetBinding(Grid.HeightProperty, canvasHeightBinding);

            TextBlock tblock1 = new TextBlock();

            tblock1.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            tblock1.VerticalAlignment = System.Windows.VerticalAlignment.Center;

            tblock1.Margin = new Thickness(0, 0, -5, 0);
            tblock1.FontWeight = FontWeights.Bold;
            tblock1.FontSize = tblock1.FontSize + 2;
            if (DashboardHelper.GetAllGroupsAsList().Contains(cbxExposureField.SelectedItem.ToString()))
            {
                tblock1.Text = value;
            }
            else
            {
                tblock1.Text = cbxExposureField.SelectedItem.ToString();
            }

            Typeface typeFace = new Typeface(new FontFamily("Global User Interface"), tblock1.FontStyle, tblock1.FontWeight, tblock1.FontStretch);
            FormattedText ftxt = new FormattedText(tblock1.Text, System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, typeFace, tblock1.FontSize, Brushes.Black);

            RotateTransform rotate = new RotateTransform(270);

            // This code works, but only if grid height is known at this point.
            //double actualCanvasHeight = exposureCanvas.Height;
            //double actualControlWidth = ftxt.Width;//tblockExposure.ActualWidth;

            //double x = Canvas.GetLeft(tblock1);

            //if (actualCanvasHeight > actualControlWidth)
            //{
            //    double diff = actualCanvasHeight - actualControlWidth;
            //    double bottom = diff / 2;
            //    Canvas.SetBottom(tblock1, bottom);
            //}

            tblock1.RenderTransform = rotate;

            exposureCanvas.Children.Add(tblock1);

            //Grid.SetColumn(tblock1, 0);
            //Grid.SetRow(tblock1, 1);
            //gridOuter.Children.Add(tblock1);

            gridOuter.Children.Add(exposureCanvas);

            TextBlock tblock2 = new TextBlock();
            tblock2.Name = "tblockOutcomeGridHeader";
            tblock2.FontWeight = FontWeights.Bold;
            tblock2.FontSize = tblock1.FontSize + 2;
            tblock2.Text = cbxOutcomeField.SelectedItem.ToString();
            tblock2.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            tblock2.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            Grid.SetColumn(tblock2, 1);
            Grid.SetRow(tblock2, 0);
            gridOuter.Children.Add(tblock2);

            sv.Content = gridOuter;

            TextBlock txtDisclaimerLabel = new TextBlock();
            txtDisclaimerLabel.Text = string.Empty;
            txtDisclaimerLabel.Margin = new Thickness(2, 8, 2, 10);
            txtDisclaimerLabel.HorizontalAlignment = HorizontalAlignment.Center;
            txtDisclaimerLabel.Tag = value;

            gridDisclaimerList.Add(txtDisclaimerLabel);

            crosstabPanel.Children.Add(sv);
            crosstabPanel.Children.Add(chiSquaregrid);
            crosstabPanel.Children.Add(txtDisclaimerLabel);

            if (string.IsNullOrEmpty(strataVar) && GadgetOptions.StrataVariableNames.Count == 0)
            {
                panelMain.Children.Add(crosstabPanel);
            }
            else
            {
                crosstabPanel.Margin = (Thickness)this.Resources["genericElementMargin"];
                expander.Margin = (Thickness)this.Resources["expanderMargin"];
                expander.IsExpanded = true;
                expander.Content = crosstabPanel;
                panelMain.Children.Add(expander);
            }

            strataChiSquareGridList.Add(chiSquaregrid);
            StrataGridList.Add(grid);
        }