kilojoules88
kilojoules88

Reputation: 51

GridView is not displayed even after databind

I have a GridView on my page that I want to bind data to, and do some sorting before the GridView is displayed but nothing is displayed. Below is my code:

  Dim dt As New DataTable
    Dim dr As DataRow

    ' define the table's schema

    dt.Columns.Add(New DataColumn("PP", GetType(String)))
    dt.Columns.Add(New DataColumn("-", GetType(String)))
    dt.Columns.Add(New DataColumn("Distance", GetType(String)))


    Dim i As Integer = 0


    ' Now Create a loop that Add data into datagridview and sort by shortest distance

    For Each r As System.Guid In arrid
        dr = dt.NewRow()
        dr("PP") = ResolveUrl(arrpic(i))
        dr("-") = Arrnames(i).ToString & " (" & arrage(i) & ")" & vbCrLf & arrgender(i) & " from " & arrlocation(i) & vbCrLf & arrcomments(i)
        dr("Distance") = arrdistance(i)

        i = +1
    Next

    GridView1.DataSource = dt.DataSet
    GridView1.DataBind()
    'SortDirection data by shortest distance
    'GridView1.Sort("Distance", SortDirection.Ascending)

Upvotes: 1

Views: 2111

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460108

The GridView is not displayed because it's empty.

You haven't added the new rows to the DataTable, therefore either use table.Rows.Add(newRow) or table.Rows.Add() instead which returns the already added (empty) row:

For Each r As System.Guid In arrid
    Dim dr = dt.NewRow() ' empty row not added yet
    dr("PP") = ResolveUrl(arrpic(i))
    dr("-") = Arrnames(i).ToString & " (" & arrage(i) & ")" & vbCrLf & arrgender(i) & " from " & arrlocation(i) & vbCrLf & arrcomments(i)
    dr("Distance") = arrdistance(i)
    dt.Rows.Add(dr) ' now added
    i = +1
Next

or

For Each r As System.Guid In arrid
    Dim dr = dt.Rows.Add() ' empty row now already added
    dr("PP") = ResolveUrl(arrpic(i))
    dr("-") = Arrnames(i).ToString & " (" & arrage(i) & ")" & vbCrLf & arrgender(i) & " from " & arrlocation(i) & vbCrLf & arrcomments(i)
    dr("Distance") = arrdistance(i)
    i = +1
Next

I prefer the second way if possible, it saves one line and prevents issues like this.

Upvotes: 1

Related Questions