2

How can I show a text in the grey part of a DataGridView when it's empty.

I found this example but not work in VB.net

GridView1.EmptyDataText="No Records Found";
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • `EmptyDataText` is a property for Web Forms `GridView` control. For Windows Forms, you need to render the text yourself. – Reza Aghaei Feb 09 '19 at 18:02

1 Answers1

3

EmptyDataText is a property of Web Forms GridView control. In Windows Forms, to show a text when DataGridView doesn't have any row, you need to render the text yourself. To do so, you can handle Paint event of DataGridView and render the text using TextRenderer.DrawText.

C#

private void dataGridView1_Paint(object sender, PaintEventArgs e)
{
    if (dataGridView1.Rows.Count == 0)
        TextRenderer.DrawText(e.Graphics, "No records found.",
            dataGridView1.Font, dataGridView1.ClientRectangle,
            dataGridView1.ForeColor, dataGridView1.BackgroundColor,
            TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
}

VB.NET

Private Sub DataGridView1_Paint(sender As Object, e As PaintEventArgs) _
    Handles DataGridView1.Paint
    If DataGridView1.Rows.Count = 0 Then
        TextRenderer.DrawText(e.Graphics, "No records found.",
            DataGridView1.Font, DataGridView1.ClientRectangle,
            DataGridView1.ForeColor, DataGridView1.BackgroundColor,
            TextFormatFlags.HorizontalCenter Or TextFormatFlags.VerticalCenter)
    End If
End Sub
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • In what method could I paint the text "loading data" while executing my query in the background? – Julio Romero Feb 09 '19 at 20:44
  • To show loading, I'd suggest using [this solution](https://stackoverflow.com/a/39142535/3110834). – Reza Aghaei Feb 10 '19 at 03:07
  • Thanks. I have resolved the problem using the example posted above. What I did was to use an event that indicates when the data load in background has finished. Then, using a flag I managed the text showing in the textRenderer. While the background worker is running I show the text "loading data". Once the background worked has finished I show the data or in the case that the datagridView.rows.cout =0 the text "No records found" – Julio Romero Feb 10 '19 at 04:10
  • Yes you can do it as well. However the linked post is also a good example of showing a loading animation + using async/await pattern to load data. – Reza Aghaei Feb 10 '19 at 04:36