Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show "No record found" message on a WPF DataGrid when it's empty

If there is no record available, I want to add a TextBlock on data grid, below the header, showing the message "No Record Found."

Consider the attached image for reference.alt text

like image 281
pchajer Avatar asked Jan 14 '11 02:01

pchajer


2 Answers

Its been a long time since the question has been posted. But I thought this might be useful to someone else.

<Window.Resources>
   <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</Window.Resources>

<DataGrid Name="dgProjects" ItemsSource="{Binding Projects}" AutoGenerateColumns="True" />

<TextBlock Text="Employee has no projects" Visibility="{Binding Items.IsEmpty, Converter={StaticResource BooleanToVisibilityConverter}, ElementName=dgProjects}" />

For simplicity purpose I have set AutoGenerateColumns="True". Please define the columns. This way when a empty datasource is bound, the column names will be shown along with 'Empty row' message.

like image 187
VisDev Avatar answered Sep 22 '22 18:09

VisDev


Finally I am able to findout the way.

  1. When the grid in empty, add a default row on grid
  2. Create a RowDetailTemplate which contain a text block with a message "No Record Found"

    <DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="No Record Found" Width="400"></TextBlock>
            </StackPanel>
        </DataTemplate>
    </DataGrid.RowDetailsTemplate>
    
  3. Set the style on datagrid

    <DataGrid.Style>
        <Style TargetType="DataGrid">
            <Setter Property="RowDetailsVisibilityMode" Value="Collapsed"></Setter>
            <Style.Triggers>
                <DataTrigger Binding="{Binding DataContext.IsRecordExists, 
                                        RelativeSource={RelativeSource Mode=FindAncestor,
                                        AncestorType={x:Type local:MainWindow}}}" Value="false">
                    <Setter Property="RowHeight" Value="0"></Setter>
                    <Setter Property="RowDetailsVisibilityMode" Value="Visible"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Style>
    

By default (record available on datagrid) row detail template will be collapsed.

DataTrigger that checks CLR poperty, if it is false then show the row detail template.

The reason for setting the rowheight as 0 to hide the default row which we haved added on 1st step.

like image 23
pchajer Avatar answered Sep 19 '22 18:09

pchajer