Reputation: 4590
I have this GridView
that I'm trying to bind data to and I need to create a new class with all my properties and display them in the Grid
. Is this supposed to be a list collection because I tried a list but the Grid
wasn't able to find the names in the list.
I usually don't deal with collections. So, I'm not very familiar with it. I just need some guidance on how this should be. I know I need a class for my collection and my properties are strings.
//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>
Upvotes: 1
Views: 5184
Reputation: 5274
1) Create class in separate file... like Product.cs
public class Product
{
public string Title { get; set; }
public string SmallImage { get; set; }
}
2) In your 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();
}
}
Upvotes: 3
Reputation: 460138
Assuming your class is called Product
and has these two properties:
public class Product{
string Title;
string SmallImage;
}
You have to declare this class somewhere in the codebehind, best in another file than the page's codebehind file (since you probably want to reuse the class somewhere else).
Now you have to fill a List<Product>
in the codebehind file of this aspx page. I would suggest Page_Load
.
Note that you should do that only if(!IsPostBack)
, otherwise you're overwriting all changes made by the user and you're preventing events from being triggered.
Then you need to use this list as DataSource
for the GridView
and DataBind
it afterwards.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
List<Product> list = new List<Product>();
Product prod = new Product();
// set the properties
list.Add(prod);
// add other products
gridView1.DataSource = list;
gridView1.DataBind();
}
}
Upvotes: 0