user1055487
user1055487

Reputation: 261

asp.net GridView IF empty show message

I've got a grid view. I want it to say "you have nothing to show" if there are no details.

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound


    If GridView1.Rows.Count = 0 Then
        Lblemptygridview.Text = "you do no details to show"

    Elseif e.Row.RowType = DataControlRowType.DataRow then
        Dim datakey As String = GridView1.DataKeys(e.Row.RowIndex).Value.ToString()

    End If


End Sub

However; it seems to be working backwards and showing the message when there is data to display in the gird view and continues to be a blank page when there is not data to display in the grid view.

I've tried a variety of combinations with the below IF statement below but no success.

Upvotes: 2

Views: 13695

Answers (3)

JohnJ
JohnJ

Reputation: 11

Just a suggestion.. Instead of showing "you have nothing to show" in a gridview which looks outdated, why don't you make it fancy?? You can do

        Dim dt As DataTable = getDatatable()

        If Not dt Is Nothing AndAlso dt.Rows.Count > 0 Then
            GridView1.datasource = dt
            GridView1.databind()
            div.style.add("display", "none")
        Else
            GridView1.visible = False
            'Add some fancy style here to show no record
            div.style.add("display", "block")
        End If

thanks

Upvotes: 1

Gobbledigook
Gobbledigook

Reputation: 472

This is more of an addendum to Icarus's answer, adding a bit of context as to why your solution does not work. (For educational purposes).

RowDataBound is called when a Row is bound to the gridview. This basically means that this is called for every row in the grid view.

Now, the reason why your solution doesn't work, is that if your GridView simply has nothing in it, RowDataBound will not be called.

The reason why you're getting 'No Data Found' when you DO have data, is because the first time the if statement runs when loading a GridView, the GridView (at the time of execution) has no Rows, which results in your if statement being true.

Just something to keep in mind.

Upvotes: 4

Icarus
Icarus

Reputation: 63972

Instead, use the EmptyDataTemplate:

 <emptydatatemplate>
        No Data Found.  
    </emptydatatemplate> 

Upvotes: 11

Related Questions