2012-08-29 46 views
-1

我要綁定的GridView和我的自定義實體whitch我從數據庫 填充的實例,但我得到的錯誤不能設置爲一個實例 對象引用對象 我知道錯誤是從我gridlink 類時,選擇新的要設置爲鏈接財產 在這一行:link = { linkName = "tyr", linkSrc = "ytr" }, ,因爲當我earase它的錯誤停止和GridView綁定 感謝C#LINQ選擇新類錯誤:未將對象引用設置到對象

public class gridcolumns 
{ 

    public decimal cost { get; set; } 
    public Int32 count { get; set; } 
    public gridlink link { get; set; } 

    public gridcolumns() 
    { 

     // TODO: Complete member initialization 
    } 
} 

public class gridlink 
{ 
    public string linkName { get; set; } 
    public string linkSrc { get; set; } 

    public gridlink() 
    { 

    } 
} 
protected void Page_Load(object sender, EventArgs e) 
{ 
    Data281DataContextDataContext conx = new Data281DataContextDataContext(); 
    List<tbl_2_CheckReqNo_NotValid> allresult = conx.tbl_2_CheckReqNo_NotValids.ToList(); 
    gridcolumns lastMantWithDate = new gridcolumns(); 
    if (Request.QueryString.Count == 0) 
    { 
     var lastMantWithDaste = from pe in allresult //where allresult != null 
           orderby Convert.ToDecimal(pe.mandeh) descending 
           group pe by pe.mant into grouped 
           where grouped != null 
           select new gridcolumns 
           { 
            link = { linkName = "tyr", linkSrc = "ytr" }, 
            cost = grouped.Sum(g => Convert.ToDecimal(g.mandeh)), 
            count = grouped.Count(), 

           }; 

     GrdOstan.DataSource = lastMantWithDaste; 
     GrdOstan.DataBind(); 
    } 
+0

Stacktrace?.... –

+0

可能重複[什麼是.NET中的NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) –

+0

什麼是是'pe.mandeh'和'pe.mant'的類型嗎? –

回答

4

你應該實例化一個gridlink這樣的:

link = new gridlink { linkName = "tyr", linkSrc = "ytr" }, 

想想看,每件商品的查詢生成創建gridcolumns目的。該對象的link屬性最初爲null;在嘗試使用它之前,您應該將其設置爲new gridlink

+0

謝謝我的問題解決 –

3

你可能需要

link = new gridLink { linkName = "tyr", linkSrc = "ytr" } 

,而不是

link = { linkName = "tyr", linkSrc = "ytr" } 
1

替換此:

select new gridcolumns 
      { 
      link = { linkName = "tyr", linkSrc = "ytr" }, 

有了:

select new gridcolumns 
      { 
      link = new gridlink { linkName = "tyr", linkSrc = "ytr" }, 

您需要使用new關鍵字

0

在您的線路以實例gridLink類型的新對象:

link = { linkName = "tyr", linkSrc = "ytr" } 

你需要「新gridlink」,像這樣:

link = new gridlink { linkName = "tyr", linkSrc = "ytr" } 

就個人而言,我認爲這是不幸的是,你的代碼編譯。如果我嘗試過:

List<gridlink> links = new List<gridlink>(); 
links.Add({ linkName = "tyr", linkSrc = "ytr" }); 

我會正確地得到一堆語法錯誤。

添加new gridlink應解決此問題。

相關問題