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
dpdmembersAsked:
Who is Participating?
 
CodeCruiserConnect With a Mentor Commented:
Then try this approach

http://forums.asp.net/t/1806946.aspx/1?Convert+IQueryable+to+Datatable

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

You are using LINQDataSource and you are trying to get a DataTable out? That would not work.
0
 
dpdmembersAuthor Commented:
What will work then?
0
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.

 
YZlatCommented:
try

Dim dt As New DataTable()
dt = datagrid.DataSource As DataTable
0
 
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

0
 
YZlatCommented:
if that does not work, try

Dim bsource As BindingSource = CType(datagrid.DataSource, BindingSource)
Dim dt As DataTable = CType(bsource.DataSource, DataTable)
0
 
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
0
 
Rajar AhmedConsultantCommented:
http://forums.asp.net/t/1783073.aspx/1

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 - http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx

This demo will makes you clear .
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBox ID="CheckBox1" runat="server" Text="Bind gridview on Every postback" />
    <asp:DataGrid ID="gvData" runat="server" Width="50px" 
         AutoGenerateColumns="true" >
</asp:DataGrid>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return validateForm();" />
    </div>
    </form>
</body>
</html>
'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
            gvData.DataBind()
        End If
    End Sub

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            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
            Response.Write(ex.Message)
        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"))

        dt.Columns.Add(idCoulumn)
        dt.Columns.Add(nameCoulumn)

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

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

        ds.Tables.Add(dt)
        Return ds
    End Function
End Class

Open in new window

0
 
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")
      TaskGridView.DataBind()

    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.
0
 
CodeCruiserCommented:
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.
0
 
dpdmembersAuthor Commented:
Do you have example code for that suggestion?
0
 
CodeCruiserCommented:
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?
0
 
dpdmembersAuthor Commented:
Dim ds = (From xx In _Context.TableName
                          Order By xx.Surname Ascending, xx.Firstname Ascending
                          Select xx)

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

'CopyToDataTable' is not a member of 'System.Linq.IQueryable(Of TableName)'
0
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.