2011-07-04 30 views
1

我在GridView中問題與數據源和GridView

var source = from p in allComments 
     select new {p.Img, p.Name, p.Comment}; 
      GridView1.DataSource = source; 
      GridView1.DataBind(); 

把這個作爲數據源,我得到這個:

The DataSourceID of 'GridView1' must be the ID of a control of type IDataSource. 

ID爲「SqlDataSource1」控制找不到。

我的GridView標記:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
     style="z-index: 1; left: 317px; top: 374px; position: absolute; height: 597px; width: 666px" 
     BackColor="#CCCCCC" BorderColor="#999999" 
     BorderWidth="0px" CellPadding="4" CellSpacing="2" 
     DataSourceID="SqlDataSource1" ForeColor="Black" AllowPaging="True" 
     onrowdatabound="GridView1_RowDataBound"> 

<Columns> 
     <asp:TemplateField HeaderText="#"> 
         <HeaderStyle Width="500px" /> 
         <ItemStyle Width="500px" /> 
         <ItemTemplate> 
          <asp:Label ID="lblMessage" runat="server" Text='<%# Bind("Comment") %>'></asp:Label> 
         </ItemTemplate> 
     </asp:TemplateField> 

      <asp:TemplateField HeaderText="#"> 
         <HeaderStyle Width="100px" /> 
          <ItemStyle Width="100px" /> 
         <ItemTemplate> 
          <asp:Image ID="imgName" runat="server" imageUrl='<%# Bind("Img") %>'></asp:Image><br /> 
          <asp:Hyperlink ID="hyperLink" runat="server" Text='<%# Bind("Name") %>' ></asp:Hyperlink> 
         </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 

     </asp:GridView> 
+1

我想你複製和從其他網頁粘貼代碼,並忘記刪除的DataSourceID =「SqlDataSource1」 :) –

回答

2

在GridView刪除DataSourceID="SqlDataSource1",當你在代碼中設置背後的數據源..

var source = from p in allComments 
select new {p.Img, p.Name, p.Comment}; 
GridView1.DataSource = source; 
GridView1.DataBind(); 

您可以指定DataSourceID or DataSource,但不能兩者都做。

編輯:繼續您的意見,您在尋呼問題,以處理分頁,你必須再次綁定數據。

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) 
{ 
    GridView1.PageIndex = e.NewPageIndex; 
    var source = from p in allComments 
       select new { p.Img, p.Name, p.Comment }; 
    GridView1.DataSource = source; 
    GridView1.DataBind(); 
} 
+0

的數據源不支持服務器端數據分頁.---我VAR LINQ聲明不支持分頁:( –

+0

你的問題是分頁,我已經更新了我的答案,現在就試試吧。 –

+0

好吧,它沒有通過例外..但我的數據源沒有綁定在頁面上加載權利否,但在頁面索引更改HMM。 ..如果頁面索引沒有改變? –

0

你已經得到了屬性DataSourceID="SqlDataSource1",該錯誤信息表明沒有SqlDataSource在代碼中的Id SqlDataSource1

因此,您需要刪除該屬性才能將其從代碼隱藏中綁定。

你的GridView decleration應該是這樣的,而不是:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    style="z-index: 1; left: 317px; top: 374px; position: absolute; height: 597px; width: 666px" 
    BackColor="#CCCCCC" BorderColor="#999999" 
    BorderWidth="0px" 
    CellPadding="4" CellSpacing="2" 
    ForeColor="Black" AllowPaging="True" 
    onrowdatabound="GridView1_RowDataBound"> 

您現在可以綁定在GridView沒有這個問題,你只能有其中的一個設定。您可以使用DataSource屬性從代碼中綁定。或者您指定屬性DataSourceId

0

刪除DataSourceID="SqlDataSource1"