数据源和gridview的问题

时间:2011-07-04 06:47:03

标签: c# .net asp.net linq 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>

3 个答案:

答案 0 :(得分:2)

从Gridview中删除DataSourceID="SqlDataSource1",因为您在Code中设置了DataSource ..

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

答案 1 :(得分:0)

您已获得属性DataSourceID="SqlDataSource1",错误消息表明代码中没有SqlDataSource ID为SqlDataSource1

因此,您需要删除该属性才能将其与代码隐藏绑定。

你的网格视图去除应该是这样的:

 <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

答案 2 :(得分:0)

删除DataSourceID="SqlDataSource1"

相关问题