1

The WPF form has TabControl with three TabItems. Each TabItem contains DataGrid. And I would like to populate DataGrid in case if according TabItem selected.

C#

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    SetA_DG();
}

public void SetA_DG()
{
   var sourcea UIAdapter.GetSourceA();
   DataGrid_A.ItemsSource = sourcea;
}   

public void SetB_DG()
{
   var sourceb UIAdapter.GetSourceB();
   DataGrid_B.ItemsSource = sourceb;
}

public void SetC_DG()
{
   var sourcec UIAdapter.GetSourceC();
   DataGrid_C.ItemsSource = sourcec;
}
private void ABC_TC_SelectionChenged(object sender, SelectionChangedEventArgs e)
//{
   //var sTabItem = ABC_TC.SelectedItem as TabItem;

   //switch (sTabItem.Name)
   //{
      //case "A_TI":
         //SetA_DG();
         //break;
      //case "B_TI":
         //SetB_DG();
         //break;
      //case "C_TI":
         //SetC_DG();
         //break;
  //}
     
   {
       var employees = GetEmployees();
       TabControl tabControl = (TabControl)sender;
       var selectedIndex = tabControl.SelectedIndex;
       TabItem tabItem = (TabItem)tabControl.SelectedItem;
       Grid grid = (Grid)tabItem.Content;
       var dataGrid = grid.GetChildOfType<DataGrid>();

       dataGrid.ItemsSource = employees;
   }
}

When I run application I get error message: System.NullReferenceException: 'Object reference not set to an instance of a object.' dataGrid was null. The execution stop on line: dataGrid.ItemsSource = employees;

XAML

`        <TabControl x:Name="ABC_TC" TabStripPlacement="Top" BorderThickness="0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" SelectionChanged="ABC_TC_SelectionChanged">
        <TabItem x:Name="A_TI" IsSelected="True" Header="AAA" >
            <DataGrid Name="A_DG" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" Width="250" SortMemberPath="Name" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Description" Binding="{Binding Path=Description}" Width="250" SortMemberPath="Description" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Active" Binding="{Binding Path=IsActive}" Width="50" SortMemberPath="IsActive" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Created On" Binding="{Binding Path=CreatedOn, StringFormat='{}{0:MM/dd/yyyy}'}" Width="110" SortMemberPath="CreatedOn" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Created By" Binding="{Binding Path=CreatedBy}" Width="100" SortMemberPath="CreatedBy" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Updated On" Binding="{Binding Path=UpdatedOn, StringFormat='{}{0:MM/dd/yyyy}'}" Width="110" SortMemberPath="UpdatedOn" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Updated By" Binding="{Binding Path=UpdatedBy}" Width="100" SortMemberPath="UpdatedBy" IsReadOnly="True"/>
                </DataGrid.Columns>
            </DataGrid>
        </TabItem>
        <TabItem x:Name="B_TI" IsSelected="True" Header="BBB" >
            <DataGrid Name="B_DG" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" Width="250" SortMemberPath="Name" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Email" Binding="{Binding Path=Email}" Width="250" SortMemberPath="Email" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Created On" Binding="{Binding Path=CreatedOn, StringFormat='{}{0:MM/dd/yyyy}'}" Width="110" SortMemberPath="CreatedOn" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Created By" Binding="{Binding Path=CreatedBy}" Width="100" SortMemberPath="CreatedBy" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Updated On" Binding="{Binding Path=UpdatedOn, StringFormat='{}{0:MM/dd/yyyy}'}" Width="110" SortMemberPath="UpdatedOn" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Updated By" Binding="{Binding Path=UpdatedBy}" Width="100" SortMemberPath="UpdatedBy" IsReadOnly="True"/>
                </DataGrid.Columns>
            </DataGrid>
        </TabItem>
        <TabItem x:Name="C_TI" IsSelected="True" Header="CCC" >
            <DataGrid Name="C_DG" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" Width="250" SortMemberPath="Name" IsReadOnly="True"/>
                    <DataGridTextColumn Header="IsActive" Binding="{Binding Path=IsActive}" Width="50" SortMemberPath="Isactive" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Created On" Binding="{Binding Path=CreatedOn, StringFormat='{}{0:MM/dd/yyyy}'}" Width="110" SortMemberPath="CreatedOn" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Created By" Binding="{Binding Path=CreatedBy}" Width="100" SortMemberPath="CreatedBy" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Updated On" Binding="{Binding Path=UpdatedOn, StringFormat='{}{0:MM/dd/yyyy}'}" Width="110" SortMemberPath="UpdatedOn" IsReadOnly="True"/>
                    <DataGridTextColumn Header="Updated By" Binding="{Binding Path=UpdatedBy}" Width="100" SortMemberPath="UpdatedBy" IsReadOnly="True"/>
                </DataGrid.Columns>
            </DataGrid>
        </TabItem>
    </TabControl>

`

How to fix the problem?

Thanks.

eugz
  • 39
  • 1
  • 6

1 Answers1

0

To achieved it filling of the datagrid must be inside of this event TabControl_SelectionChanged.

 private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var productList = getProductList();
        TabControl tabControl = (TabControl)sender;
        var selectedIndex = tabControl.SelectedIndex;
        TabItem tabItem = (TabItem)tabControl.SelectedItem;
        Grid grid = (Grid)tabItem.Content;
        var dataGrid = grid.GetChildOfType<DataGrid>();

        dataGrid.ItemsSource = productList;
    }

I used a GetChildOfType method for easier getting of the control you can check it on this answer.

OUTPUT 1:
Output 1
OUTPUT 2:
enter image description here

I hope it helps. Happy coding.

tontonsevilla
  • 2,649
  • 1
  • 11
  • 18
  • 1
    Hi tontonsevilla. Thank for replay. When I added GetChildOfType method like you suggested I got error message: "Extension method must be defined in non-generic static class" How to fix this error? Or may be do you know another way to populate DataGrid in selected TabItem? Thanks. – eugz Aug 09 '20 at 17:17
  • @eugz can you please show how you're GetChildOfType method is implemented? Also make sure that it is in a separate public static class Extensions. – tontonsevilla Aug 09 '20 at 22:58
  • I copy code of method from the link: `public static T GetChildOfType(this DependencyObject depObj) where T : DependencyObject { if (depObj == null) return null; for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) { var child = VisualTreeHelper.GetChild(depObj, i); var result = (child as T) ?? GetChildOfType(child); if (result != null) return result; } return null; }` And insert it into my **class**: `public partial class Employees { .... }` – eugz Aug 09 '20 at 23:52
  • @eugz dont put it in your partial class instead create a new class like public static class Extension { public static T GetChildOfType(...)} – tontonsevilla Aug 10 '20 at 00:49
  • I created Extension class and past GetChildOfType() method. Then I used code from your post for my TabControl_SelectionChanged(). But when I ran application I got error on line dataGrid.ItemsSource = employeeList: **System.NullReferenceExeption:** Object reference not set to an instance of an object.' **dataGrid** was null. How to fix the error? Thanks. – eugz Aug 10 '20 at 01:40
  • can you post your TabControl_SelectionChanged codes and the XAML so that we can have a clearer view on what is the issue. – tontonsevilla Aug 10 '20 at 01:41
  • How to send code and XAML? I never did it in stackoverflow. And the comment has limitation of characters. Thanks. – eugz Aug 10 '20 at 13:30
  • @eugz just update your post add it below. pasting code the same as what you are in your post. – tontonsevilla Aug 10 '20 at 13:34
  • I updated my post by add code for Tabcontrol_SelectionChanged like you suggested and commented previous version. And also added XAML code of TabControl. Thanks. – eugz Aug 10 '20 at 18:02