2015-12-23 72 views
6

我想用代碼創建gridview。我的代碼是:如何在c#後面的代碼中添加gridview與objectdatasource?

GridView gdvList = new GridView(); 
gdvList.ID = "gdvList" ; 
TemplateField tField = new TemplateField(); 
BoundField dateBF = new BoundField(); 
dateBF.DataField = "Date"; 
gdvList.Columns.Add(dateBF); 
BoundField countResponse = new BoundField(); 
countResponse.DataField = "CountResponse"; 
gdvList.Columns.Add(countResponse); 
ObjectDataSource ods = new ObjectDataSource(); 
ods.ID = "ods"; 
ods.TypeName = "Project.BLLQuestion"; 
ods.SelectMethod = "GetByGroupID"; 
ods.SelectParameters["GroupID"] = new Parameter("inGroupID", DbType.Int32, "0"); 
ods.DataBind(); 
gdvList.DataSource = ods; 
gdvList.DataBind();  

此代碼不能正常工作,以及如何添加模板列別:

<asp:TemplateField ItemStyle-CssClass="GridItemTemplateField"> 
    <ItemTemplate> 
     <a href="Question.aspx?id=<%# Eval("ID")%>"><%# Eval("Content").ToString().PadRight(140).Substring(0,140).TrimEnd()+"..." %></a> 
    </ItemTemplate> 
</asp:TemplateField> 

怎麼能行呢?

+0

爲什麼你想從代碼生成網格? – User2012384

+0

我們有組動態。因此,我們需要它 – shahroz

+0

那麼爲什麼不使用中繼器呢? – User2012384

回答

1
  1. 您需要設置網格的DataSourceID屬性,而不是DataSource
  2. 有沒有必要運行DataBind()方法ObjectDataSource
  3. 確保在Page上添加了兩個控件ObjectDataSourceGridView

試試這個:

ObjectDataSource ods = new ObjectDataSource(); 
    ods.ID = "ods"; 
    ods.TypeName = "Project.BLLQuestion"; 
    ods.SelectMethod = "GetByGroupID"; 
    ods.SelectParameters["GroupID"] = new Parameter("inGroupID", DbType.Int32, "0"); 

    Page.Controls.Add(ods); 

    GridView gdvList = new GridView(); 
    gdvList.ID = "gdvList" ; 
    gdvList.DataSourceID = "ods"; 

    BoundField dateBF = new BoundField(); 
    dateBF.DataField = "Date"; 
    gdvList.Columns.Add(dateBF); 

    BoundField countResponse = new BoundField(); 
    countResponse.DataField = "CountResponse"; 
    gdvList.Columns.Add(countResponse); 

    Page.Controls.Add(gdvList); 

    gdvList.DataBind(); 

根據你的第二個問題。嘗試用HyperLinkField代替TemplateField。詳情請點擊here

相關問題