If I have the following ASP.NET code (it's not complete - obviously there's a lot missing, but none of it matters):
<asp:GridView>
<Columns>
<asp:TemplateField>
<ItemTemplate>
My Label: <asp:Label />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
My Text Box: <asp:TextBox />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And if I have something like this in the CodeBehind:
Private MyListOfObjects As List(Of MyObject)
...
Public Class MyObject
Public MyTextBoxString as String
Public MyLabelString as String
End Class
How can I bind the GridView so that one row is equivalent to one item in my MyListOfObjects
list, and so that the data will populate and persist across page loads or postbacks? I've never done custom databinding like this before, so a full explanation would be very helpful. All the tutorials I've come across so far only talk about using GridViews directly with Database query results, and that's not what I need.
Thanks!
Use the DataBind() method to bind data from a data source to the GridView control. This method resolves all data-binding expressions in the active template of the control. The DataBind method is called automatically if the DataSourceID property of the GridView control refers to a valid data source control.
The GridView control is used to display the values of a data source in a table. Each column represents a field, while each row represents a record. The GridView control supports the following features: Binding to data source controls, such as SqlDataSource. Built-in sort capabilities.
Just set the datasource of the gridview to your object.
MyGridView.DataSource = myList
MyGridView.DataBind()
Here's a very similiar post:
Binding a method that returns List<employee> to a gridview
Looks like you are using a list in vb.net. Remember lists can hold integers, strings, dates, objects (these include user defined types (your object)). So you can bind a gridview to a list object by setting the datasource property to your list.
In the above example, myList, might hold a ton of employee objects, etc. So assign it to the datasource and .DataBind()
and voila a gridview with each row containing your object.
You can do something like
My Label: <asp:Label id="myLabel" runat="server" Text='<%# Eval("MyTextBoxString") %>' />
in the markup and similar stuff for your textbox.
GridView1.DataSource = MyListOfObjects
GridView1.DataBind()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With