views:

102

answers:

3

I've been working on this for a few days now I every time I come back to this problem I just don't see why it's not working correctly.

I'm trying to bind a DataTable to a GridView control that I create Dynamically. I create the GridView control, add it to a table, and then assign the DataSource property to my DataTable.

This is the code:

Table tbl = new Table();

DataTable dattbl = Core.Transreports(Request.QueryString["itemaddress"], Request.QueryString["docnum"], Request.QueryString["docid"]);

GridView dg = new GridView() { ID = "dg", AllowPaging = true, PageSize = 10 };

TableRow tr = new TableRow();

TableCell tc = new TableCell();
tc.Controls.Add(dg);
tc.ColumnSpan = 10;
tr.Cells.Add(tc);

tbl.Rows.Add(tr);

if (dattbl.Rows.Count > 0)
{
    dg.DataSource = dattbl;
    dg.DataBind();
}

So when I get the the last line, where I execute the DataBind (dg.DataBind()) method is where I'm getting the null reference exception.

I'm not really sure why I'm running into this error, and have not yet found a solution. I've checked to make sure there are no null values in the DataTable as well, and there are none. So I'm at a loss.

Help me stack overflow, you're my only hope.

+1  A: 

I replaced your call to Core.Transreports(...) with a dummy DataTable and could not reproduce this. Can you provide more info? What does the stack trace say? How does Core.Transreports() work?

Rex M
@Rex, Agreed, I have done the same thing and no exception
Nathan Koop
I did that with no exception as well...hmmmm. Well basically Core.Transreports() is a method that builds a SQL Query, calls another function that executes the Query and returns a DataTable.
CrowderSoup
A: 

Your code looked like this:

if (dattbl.Rows.Count > 0){    dg.DataSource = dattbl;    dg.DataBind();}

With an exception "on the last line".

Are you sure it's not the dattbl that is null?

Carra
Sorry, for some weird reason my code was reformatted by stack overflow... there is line breaks in my source.And yes, I'm sure. I've tried commenting out where I do the DataBinding and then just outputting each column / row of the datatable individually. That works with no errors.
CrowderSoup
A: 

Since you're getting the error because the gridview is not a control on the page, what you need to do is put an <asp:GridView> in the page, or put it in some asp control. Then place that control on the page. Here is a sample:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Sample.ascx.cs" Inherits="Contacts" %>

<asp:GridView id="sample" runat="server" AllowPaging="true" PageSize="10"></asp:GridView>

Then you can reference that gridview from the code behind like so:

sample.DataSource = dattbl;
sample.DataBind();
Brett
@Brett, thanks for the help!
CrowderSoup