Search code examples
c#wpfdatagridstackpanel

Place multiple scrolling data tables into a grid on a stack panel WPF


I am new to WPF and XAML coming from VB.NET and WinForms so I apologize if this post is off. I am trying to set up multiple sql binded data tables into a stack panel that has a grid in it. The stack panel has a grid which I was then hoping to place multiple data tables in so that it would be a "row" of data tables. I have ran into a problem where each data table has more entries than the data table has space for and there is no scroll bar. I tried using a scroll viewer but was unsuccessful and all the posts I have found so far have not been able to help me due to the fact they will force me to re-create my xaml tree. Here is my code so far.

------XAML-------

 <Window x:Class="Lines.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="251.7" Width="1058">

<Grid x:Name="GridMain">
    <StackPanel x:Name="StackMain" HorizontalAlignment="Left" Height="100" Margin="10,10,0,0" VerticalAlignment="Top" Width="1030" >
        <TextBlock FontSize="18" Foreground="Black" FontWeight="Bold" Text="Line 2" HorizontalAlignment="Center" />
        <Grid x:Name="Line2Information">
            <ScrollViewer x:Name="SVLine2HotParts" HorizontalAlignment="Left">
                <DataGrid x:Name="DGLine2HotParts">
                </DataGrid>
            </ScrollViewer>
        </Grid>
    </StackPanel>
</Grid>

---------------------------C#----------------

             //SQL command fill 
        SqlConnection conn = new SqlConnection(Connectionstring);
        SqlDataAdapter da = new SqlDataAdapter("SELECT * from Table", conn);
        DataTable ds = new DataTable();
        da.Fill(ds);
        Datagrid.ItemsSource = ds.DefaultView;

So in the XML you can see I have a textblock with a location and then on the next "Row" down I will be setting multiple data tables, hopefully along a grid. Any help?


Solution

  • You're asking a very broad question here. I think you should do some research into MVVM. It helps to structure a WPF design. The general idea is that you bind an element in the XAML (in the View) to a public property in the ViewModel. Then changes to the property result in changes to the element and hence the UI. The Model contains the data and will concerned with getting data from the DB. You'll likely have a property of type ObservableCollection in the ViewModel bound to the Datagrid. The ViewModel would populate the ObservableCollection from the Model. With MVVM you have little code behind. One comment on your "SQL command fill", I'm assuming this is in your code behind. You need to reference DGLine2HotParts.Datacontext or DGLine2HotParts.ItemSource to add data to the grid. This is an attempt to point you in a particular direction rather than a comprehensive answer.