简体   繁体   中英

Null Reference Exception when binding DataTable to GridView

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.

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?

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM