?
Solved

Gridview Datasource

Posted on 2012-09-04
14
Medium Priority
?
1,001 Views
Last Modified: 2012-09-04
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
0
Comment
Question by:dpdmembers
  • 6
  • 4
  • 2
  • +1
14 Comments
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 38364076
>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
 

Author Comment

by:dpdmembers
ID: 38364113
What will work then?
0
 
LVL 35

Expert Comment

by:YZlat
ID: 38364582
try

Dim dt As New DataTable()
dt = datagrid.DataSource As DataTable
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 18

Expert Comment

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

Open in new window

0
 
LVL 35

Expert Comment

by:YZlat
ID: 38364607
if that does not work, try

Dim bsource As BindingSource = CType(datagrid.DataSource, BindingSource)
Dim dt As DataTable = CType(bsource.DataSource, DataTable)
0
 

Author Comment

by:dpdmembers
ID: 38364914
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
 
LVL 18

Expert Comment

by:Rajar Ahmed
ID: 38365033
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
 

Author Comment

by:dpdmembers
ID: 38365163
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
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 38365184
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
 

Author Comment

by:dpdmembers
ID: 38365211
Do you have example code for that suggestion?
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 38365216
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
 

Author Comment

by:dpdmembers
ID: 38365272
Dim ds = (From xx In _Context.TableName
                          Order By xx.Surname Ascending, xx.Firstname Ascending
                          Select xx)

            Me.gridview1.DataSource = ds
            gridview1.DataBind()
0
 

Author Comment

by:dpdmembers
ID: 38365276
When I try the CopyToDataTable I get the error :

'CopyToDataTable' is not a member of 'System.Linq.IQueryable(Of TableName)'
0
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 2000 total points
ID: 38365315
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

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question