![](/img/trans.png)
[英]Binding datatable to a custom GridView control generates null reference exception
[英]Null Reference Exception when binding DataTable to GridView
我已經為此工作了幾天,每次我回到這個問題時,我只是不明白為什么它無法正常工作。
我正在嘗試將DataTable綁定到我動態創建的GridView控件上。 我創建GridView控件,將其添加到表中,然后將DataSource屬性分配給我的DataTable。
這是代碼:
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();
}
因此,當我得到最后一行時,執行DataBind( dg.DataBind() )方法的地方就是獲取空引用異常的地方。
我不太確定為什么會遇到此錯誤,並且還沒有找到解決方案。 我已經檢查以確保DataTable中也沒有null值,並且也沒有。 所以我很茫然。
幫助我堆棧溢出,您是我唯一的希望。
我用一個虛擬的DataTable替換了對Core.Transreports(...)
調用,但無法重現。 您可以提供更多信息嗎? 堆棧跟蹤說明了什么? Core.Transreports()
如何工作?
您的代碼如下所示:
if (dattbl.Rows.Count > 0){ dg.DataSource = dattbl; dg.DataBind();}
除“最后一行”外。
您確定不是dattbl為空嗎?
由於由於gridview不是頁面上的控件而出現錯誤,因此您需要在頁面中放置<asp:GridView>
或將其放置在某些asp控件中。 然后將該控件放在頁面上。 這是一個示例:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Sample.ascx.cs" Inherits="Contacts" %>
<asp:GridView id="sample" runat="server" AllowPaging="true" PageSize="10"></asp:GridView>
然后,您可以從后面的代碼中引用該gridview,如下所示:
sample.DataSource = dattbl;
sample.DataBind();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.