C # WPF Sliding Menu: Columns Not Displaying in Datagrid

I checked various links here and on the internet that dealt with various data grids not displaying data, but I did not come across one that had a similar scenario as the problem I am facing.

Doesn't update in WPF using DataGrid

WPF Doesn't display data inside datagrid

How to get data in datagrid using dataset?

DataGridView is not showing data: DataSet is empty

In C # WPF, I created an application that, when launched, comes to a main menu screen with tabs to custom pages and different buttons at the top of the page like: home, exit, update and settings. The problem I have is in my settings menu. When the user clicks the settings button from MainWindow, the SettingsMainWindow popup appears. The white section contains links that the user clicks to navigate to different settings pages, and the window to the right will navigate to the next page depending on what is clicked.

Settings Menu Main Screen

SettingsMainWindow.xaml

``                                                                                                     

    <!-- Define supported transitions -->
    <NavigationTransition:NavigationCubeTransition x:Key="CubeTransition" Duration="0:0:0.8"/>
    <NavigationTransition:NavigationSlideTransition x:Key="SlideTransition" Duration="0:0:0.8"/>
    <NavigationTransition:NavigationFlipTransition x:Key="FlipTransition" Duration="0:0:0.8"/>

    <BooleanToVisibilityConverter x:Key="bvc"/>

</Window.Resources>
<DockPanel Grid.RowSpan="5" Height="auto" HorizontalAlignment="Stretch" Name="dockPanelLogin"    VerticalAlignment="Stretch" Width="auto" Opacity="10" Grid.ColumnSpan="2" OpacityMask="{DynamicResource {x:Static SystemColors.MenuTextBrushKey}}" >
    <DockPanel.Background>
        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
            <GradientStop Color="Black" Offset="0"/>
            <GradientStop Color="White" Offset="1"/>
        </LinearGradientBrush>
    </DockPanel.Background>

    <Grid Margin="100">

        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="3*"/>
        </Grid.ColumnDefinitions>

        <DockPanel Grid.Column="0" LastChildFill="True" Margin="5">

            <!-- Each ComboBoxItem contains the transition in its Tag property
             so that the TransitionContainer can directly databind to the
             selected transition -->
            <ComboBox x:Name="transitionComboBox" SelectedIndex="0" DockPanel.Dock="Bottom" Margin="0,3,0,0">
                <!--<ComboBoxItem Tag="{StaticResource CubeTransition}">Cube</ComboBoxItem>-->
                <ComboBoxItem Tag="{StaticResource SlideTransition}">Slide</ComboBoxItem>
                <!--<ComboBoxItem Tag="{StaticResource FlipTransition}">Flip</ComboBoxItem>-->
            </ComboBox>

            <ListBox Grid.Column="0"
                 ItemsSource="{Binding Views}" IsSynchronizedWithCurrentItem="True"
                 SelectedIndex="0">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Name}" Padding="10"/>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </DockPanel>

        <Border Grid.Column="1" Margin="5" BorderBrush="#FF7F9DB9" BorderThickness="1">
            <!-- The ContentProperty is not bound directly to the SelectedItem of the ListBox because the
             GoForward property must be updated BEFORE the content changes. The CurrentContent property
             is defined in the ViewModel class and updated everytime the selection of the ListBox changes,
             after setting up the GoForward value. -->
            <NavigationTransition:NavigationPresenter 
            Content="{Binding CurrentContent}"
            Transition="{Binding ElementName=transitionComboBox, Path=SelectedItem.Tag}"
            GoForward="{Binding DataContext.GoForward, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type NavigationTransition:NavigationSlideTransition}}}"/>
        </Border>
        <!--Region Editor-->
        <Grid Grid.RowSpan="100" Grid.ColumnSpan="100"
          Background="#88000000" Visibility="{Binding IsShowingPage3View, Converter={StaticResource bvc}, FallbackValue=Collapsed}">
            <View:Page3View Margin="0, 200, 0, 0"
                                           x:Name="page3View" DataContext="{Binding}" Width="800" Height="700"/>
        </Grid>
    </Grid>
</DockPanel>

      

My problem is showing data from my access DB in the data grid on the page below. This grid should be automatically populated with the region table information on load, where the user can add additional regional information. At startup, there should be four columns shown below. I have implemented this same functionality elsewhere in the app, which is not in the menu, and it works fine. When it is debugged it shows that it reads the table correctly, but it just doesn't show or give any errors. My question is how to get this to display the required data while on the menu page.

Runtime View of Region Update Page

Page3View.xaml

<Border BorderBrush="{DynamicResource {x:Static SystemColors.HotTrackBrushKey}}" 
        BorderThickness="1" 
        Background="{DynamicResource {x:Static SystemColors.GradientActiveCaptionBrushKey}}"
        Padding="20">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="1">
            <Rectangle HorizontalAlignment="Left" Width="100" Height="6" Fill="{DynamicResource {x:Static SystemColors.MenuHighlightBrushKey}}" />
            <TextBlock FontSize="24" Foreground="#444444" FontWeight="Bold" Text="REGION-DISTRICT NAME EDITOR" />
        </StackPanel>

        <StackPanel Grid.Row="1" Height="10"/>

        <DataGrid x:Name="dg" Grid.Row="2" Height="Auto" VerticalAlignment="Stretch"
                      VirtualizingStackPanel.IsVirtualizing="True"
                      CanUserAddRows="True"
                      CanUserDeleteRows="True"
                      CanUserResizeRows="False"
                      CanUserReorderColumns="False"
                      CanUserResizeColumns="True"
                      CanUserSortColumns="False"
                        VirtualizingStackPanel.VirtualizationMode="Recycling"

                      AutoGenerateColumns="True">

        </DataGrid>

        <!--<StackPanel Orientation="Horizontal" VerticalAlignment="Top"  HorizontalAlignment="Right" Grid.ColumnSpan="4"
                    IsEnabled="{Binding TaskbarProgressValue, Converter={StaticResource ProgressBarStartButtonEnabledConverter}}">
            <Button Style="{StaticResource PanelCloseButtonStyle}" Margin="0" Click="btnClose_Click" />
        </StackPanel>-->

        <StackPanel Margin="0, 10, 0, 0" Grid.Row="4" Orientation="Horizontal" HorizontalAlignment="Right">
            <Button Height="Auto" Click="btnSubmit_Click" Content="OK" Command="{Binding ToggleRegionEditorsCommand}" CommandParameter="{StaticResource False}" Width="90"/>
            <StackPanel Width="10" />
            <Button Height="Auto" Click="btnClose_Click" Content="Cancel" Command="{Binding ToggleRegionEditorsCommand}" CommandParameter="{StaticResource False}" Width="90" />
        </StackPanel>

        <!--Added for page 3 region editor-->
        <!--<Grid Grid.RowSpan="100" Grid.ColumnSpan="100"
          Background="#88000000" Visibility="{Binding IsShowingPage3View, Converter={StaticResource bvc}, FallbackValue=Collapsed}">
            <View:Page3View Margin="0, 200, 0, 0"
                                           x:Name="page3View" DataContext="{Binding}" Width="800" Height="700"/>
        </Grid>-->

    </Grid>
</Border>

      

Page3View.xaml.cs

{
    /// <summary>
    /// Interaction logic for Page3View.xaml Region Distric Editor
    /// </summary>
    public partial class Page3View : UserControl
{
    public Page3View()
    {
        InitializeComponent();
    }

    private IDbDriver Database { get; set; }
    private DataHelper DataHelper { get; set; }

    public void Init(DataHelper dataHelper)
    {
        if (dg.ItemsSource != null)
        {
            dg.ItemsSource = null;
        }

        Database = dataHelper.Database;
        DataHelper = dataHelper;

        Query selectQuery = Database.CreateQuery("SELECT DRS, RegCode, DISTRICT, DistCode FROM [codedistrict1] ORDER BY DRS, DISTRICT");
        DataTable dt = Database.Select(selectQuery);
        dg.ItemsSource = (dt).DefaultView;
    }

    private void btnSubmit_Click(object sender, RoutedEventArgs e)
    {
        if (dg.ItemsSource != null)
        {
            DataView dv = dg.ItemsSource as DataView;
            if (dv != null && dv.Table != null)
            {
                DataTable dt = dv.Table;
                if (dt != null && Database != null)
                {
                    try
                    {
                        string querySyntax = "DELETE * FROM [codedistrict1]";
                        if (Database.ToString().ToLower().Contains("sql"))
                        {
                            querySyntax = "DELETE FROM [codedistrict1]";
                        }

                        Query deleteQuery = Database.CreateQuery(querySyntax);
                        Database.ExecuteNonQuery(deleteQuery);

                        DataRow[] rows = dt.Select(String.Empty, String.Empty, DataViewRowState.CurrentRows);

                        foreach (DataRow row in rows)
                        {
                            Query insertQuery = Database.CreateQuery("INSERT INTO [codedistrict1] (DRS, RegCode, DISTRICT, DistCode) VALUES (" +
                                "@DRS, @RegCode, @DISTRICT, @DistCode)");
                            insertQuery.Parameters.Add(new QueryParameter("@DRS", DbType.String, row[0].ToString()));
                            insertQuery.Parameters.Add(new QueryParameter("@RegCode", DbType.String, row[1].ToString()));
                            insertQuery.Parameters.Add(new QueryParameter("@DISTRICT", DbType.String, row[2].ToString()));
                            insertQuery.Parameters.Add(new QueryParameter("@DistCode", DbType.String, row[3].ToString()));
                            Database.ExecuteNonQuery(insertQuery);
                        }

                        MessageBox.Show("Changes were committed to the database successfully.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Changes were not committed to the database successfully. Error: " + ex.Message, "Failure", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    finally
                    {
                    }
                }
            }
        }
    }

    private void btnClose_Click(object sender, RoutedEventArgs e)
    {

    }
}

      

}

DataHelper.cs

public class DataHelper : DataHelperBase
{
    #region Members
    private bool _isShowingPage3View = false;
    #endregion

    #region Properties

    // Shows the region districts update page for the settings page
    public bool IsShowingPage3View
    {
        get
        {
            return this._isShowingPage3View;
        }
        set
        {
            if (!IsShowingPage3View == value)
            {
                this._isShowingPage3View = value;
                RaisePropertyChanged("IsShowingPage3View");
            }
        }
    }

  // This is for the region district editor on the settings page
    public ICommand TogglePage3ViewCommand { get { return new    RelayCommand<bool>   TogglePage3ViewCommandExecute); } }
    private void TogglePage3ViewCommandExecute(bool show)
    {
        IsShowingPage3View = show;
    }




   private void btnSettings_Click(object sender, RoutedEventArgs e)
        {
            {
                Regions.View.Page3View.Int(this.DataHelper);
            }
        }

      

With the above code, I now get the error that it does not contain a definition for Int, even though it is defined in Page3View. It should be linked to this block of code.

public void Init(DataHelper dataHelper)
    {
        if (dg.ItemsSource != null)
        {
            dg.ItemsSource = null;
        }

        Database = dataHelper.Database;
        DataHelper = dataHelper;

        Query selectQuery = Database.CreateQuery("SELECT DRS, RegCode, DISTRICT, DistCode FROM [codedistrict1] ORDER BY DRS, DISTRICT");
        DataTable dt = Database.Select(selectQuery);
        dg.ItemsSource = (dt).DefaultView;
    }

      

+3


source to share





All Articles