How to bind objectdatasource with a Gridview
UPDATE: THIS IS THE WORKING VERSION.
public DataSet GetObjects()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
var source = from p in CommentsList
select new { p.Img, p.Name, p.Comment };
dt.Columns.Add("Img");
dt.Columns.Add("Name");
dt.Columns.Add("Comment");
foreach (var item in source)
{
DataRow userDetailsRow=dt.NewRow();
userDetailsRow["Img"] = item.Img;
userDetailsRow["Name"] = item.Name;
DataRow comments = dt.NewRow();
userDetailsRow["Comment"] = item.Comment;
dt.Rows.Add(userDetailsRow);
//dt.Rows.Add(comments);
}
ds.Tables.Add(dt);
return ds;
}
My GridView columns section looks like this:
<Columns>
<asp:TemplateField HeaderText="#">
<HeaderStyle Width="500px" />
<ItemStyle Width="500px" Height="100px" />
<ItemTemplate>
开发者_如何转开发 <asp:Label ID="lblMessage" runat="server" Text='<%# Bind("Comment") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="#">
<HeaderStyle Width="100px" />
<ItemStyle Width="100px" Height="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>
UPDATE: The problem that I have got now is with the size of rows..that are huge and dont update with the content within,,,example: Header 33%, Row 33%, footer 33%..even though the content of the header is 10% of the gridview..how do i fix that?
You do not have a Img
property. Plain and simple. This is why you have problems accessing it: it does not exist.You should create the property AND populate it.
Update
You should do this:
var source = from p in CommentsList
select new { p.Img, p.Name, p.Comment };
dt.Columns.Add("User");
dt.Columns.Add("Comment");
dt.Columns.Add("Img");
and then this:
DataRow userDetailsRow=dt.NewRow();
userDetailsRow["Img"] = item.Img;
userDetailsRow["User"] = item.Name;
Fix where it applies.
You need to add a Column in your DataTable with the name of Img
before using this in DataBinding
userDetailsRow["User"] = item.Img;
should be
userDetailsRow["img"] = item.Img;
精彩评论