Gridview Datasource

How do I get the Datasource of a gridview from the code behind?

When I try the following:  

Dim dt As New DataTable()
dt = DirectCast(datagrid.DataSource, DataTable)

dt is nothing all the time even though the gridview is populated

I am using a LinqDataSource and VB
Who is Participating?
CodeCruiserConnect With a Mentor Commented:
Then try this approach

Or bind to DataTable in the first place instead of the query.
>I am using a LinqDataSource and VB

You are using LINQDataSource and you are trying to get a DataTable out? That would not work.
dpdmembersAuthor Commented:
What will work then?
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.


Dim dt As New DataTable()
dt = datagrid.DataSource As DataTable
Rajar AhmedConsultantCommented:
try this,
Dim tbl As DataSet = TryCast(datagrid.DataSource, DataSet)
Dim dt As New DataTable()
dt = tbl.Tables(0)

Open in new window

if that does not work, try

Dim bsource As BindingSource = CType(datagrid.DataSource, BindingSource)
Dim dt As DataTable = CType(bsource.DataSource, DataTable)
dpdmembersAuthor Commented:
All I am getting is the error: Object reference not set to an instance of an object.

I think this is because the datagrid.DataSource is showing a value of Nothing
Rajar AhmedConsultantCommented:

if you bind gridview on every postback..then you can get  dataset/datatable using GridView1.DataSource;

but if you are binding only one time, then you got to follow this way -

This demo will makes you clear .
<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        <asp:CheckBox ID="CheckBox1" runat="server" Text="Bind gridview on Every postback" />
    <asp:DataGrid ID="gvData" runat="server" Width="50px" 
         AutoGenerateColumns="true" >
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return validateForm();" />
'Code behind
Imports System.Data
Partial Class Vb_gvTodt
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

        Dim ds As DataSet = getDataSet()
        If CheckBox1.Checked Then
            gvData.DataSource = ds
        End If
    End Sub

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim tbl As DataSet = TryCast(gvData.DataSource, DataSet)
            Dim dt As New DataTable()
            dt = tbl.Tables(0)
            Response.Write("Success " & tbl.Tables(0).Rows.Count)
        Catch ex As Exception
        End Try
    End Sub
    Public Shared Function getDataSet() As DataSet
        Dim ds As New DataSet
        Dim dt As DataTable
        Dim dr As DataRow
        Dim idCoulumn As DataColumn
        Dim nameCoulumn As DataColumn
        Dim i As Integer

        dt = New DataTable()
        idCoulumn = New DataColumn("ID", Type.GetType("System.Int32"))
        nameCoulumn = New DataColumn("Name", Type.GetType("System.String"))


        dr = dt.NewRow()
        dr("ID") = 1
        dr("Name") = "Name1"

        dr = dt.NewRow()
        dr("ID") = 2
        dr("Name") = "Name2"

        Return ds
    End Function
End Class

Open in new window

dpdmembersAuthor Commented:
I am trying the following:

Dim dt = TryCast(Session("TaskTable"), DataTable)

    If dt IsNot Nothing Then

      'Sort the data.
      dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
      TaskGridView.DataSource = Session("TaskTable")

    End If

BUT dt is always Nothing, even though Session("TaskTable") has information from a Linq query.

Therefore it is not getting pass that point.
LINQ query is not the same as a data table. You need to convert the query to a datatable and then store it in session so you can use it later.
dpdmembersAuthor Commented:
Do you have example code for that suggestion?
There should be a CopyToDataTable method on the query object which would return you a datatable. Can you show the code you use to bind the grid?
dpdmembersAuthor Commented:
Dim ds = (From xx In _Context.TableName
                          Order By xx.Surname Ascending, xx.Firstname Ascending
                          Select xx)

            Me.gridview1.DataSource = ds
dpdmembersAuthor Commented:
When I try the CopyToDataTable I get the error :

'CopyToDataTable' is not a member of 'System.Linq.IQueryable(Of TableName)'
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.