我有这个GridView
,我正在尝试将数据绑定到,我需要创建一个包含所有属性的新类,并在Grid
中显示它们。这应该是一个列表集合,因为我尝试了一个列表,但Grid
无法在列表中找到这些名称。
我通常不处理收藏品。所以,我对它不是很熟悉。我只是需要一些指导如何。我知道我的集合需要一个类,我的属性是字符串。
//This is where I am stuck, not sure how to set these and put these in a list.
public class Product
{
string Title;
string SmallImage;
}
<form id="ResultsForm" runat="server">
<div id="SearchBox">
<asp:TextBox ID="SearchBoxText" runat="server" Height="20px" Width="400px"></asp:TextBox>
<asp:Button ID="SearchButton" runat="server" Height="30px" Width="100px" Text="Search" OnClick="SearchButton_Click" />
</div>
<div id="ResultsTable">
<asp:GridView runat="server" ID="myGrid"
OnRowCommand="MyGrid_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img src='<%#Eval("SmallImage") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<div>Title: <%#Eval("Title") %> </div>
<div>Weight: <%#Eval("Weight") %> </div>
<asp:Button runat="server" ID="GetOfferButton" CommandArgument='<%#Eval("OfferID") %>'></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
答案 0 :(得分:3)
1)在单独的文件中创建类...如Product.cs
public class Product
{
public string Title { get; set; }
public string SmallImage { get; set; }
}
2)在你的aspx.cs中
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
List<Product> lst = new List<Product>();
lst.Add(new Product(){Title="title 1", SmallImage = "some path"});
lst.Add(new Product(){Title="title 2", SmallImage = "some "});
myGrid.DataSource = lst;
myGrid.DataBind();
}
}
答案 1 :(得分:0)
假设您的班级名为Product
且具有以下两个属性:
public class Product{
string Title;
string SmallImage;
}
你必须在代码隐藏中的某个地方声明这个类,最好是在另一个文件而不是页面的代码隐藏文件中(因为你可能想在其他地方重用该类)。
现在你必须填写此aspx页面的codebehind文件中的List<Product>
。我建议Page_Load
。
请注意,您应该只执行if(!IsPostBack)
,否则您将覆盖用户所做的所有更改,并阻止事件被触发。
然后,您需要将此列表用作DataSource
的{{1}},然后GridView
使用此列表。
DataBind