Using Gridview in aspx.vb (code-behind)

asp.netcode-behindgridview

I need to create a gridview based on 2 different datasources: main and sub-cathegory. And I need to list them like below:

Productinfo
   sub-product 1
   sub-product 2

Productinfo
   sub-product 1
   sub-product 2
   sub-product 3
   sub-product 4

Etc… the thing is that both the "productinfo" and the "sub-product" are dynamic as the number of both can vary, so I would have to create a gridview within a gridview, plus the necessary filters too.

For this reason I thought it was best to do it all in code-behind, but I can't understand how to use the gridview-class in codebehind and bind it so that it actually shows something in the main aspx page.

Basically what I'm asking for is a simple example of how, when you have nothing but <asp:GridView/> in the aspx -page, can you add components to it and show it, from code-behind (vb)?

Thanks.

Best Answer

vb code:

Dim mydatatable As New DataTable
' Create columns
mydatatable.Columns.Add("field_a", Type.GetType("System.String"))
mydatatable.Columns.Add("field_b", Type.GetType("System.String"))
' Declare row
Dim myrow As DataRow
' create new row
myrow = mydatatable.NewRow
myrow("field_a") = "filed a row 1"
myrow("field_b") = "filed b row 1"
mydatatable.Rows.Add(myrow)

GridView1.datasource = mydatatable
gridview1.databind()

aspx code:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" EmptyDataText="if im not at my desk im at the balcony contemplating suicide" >
<Columns></Columns>
</asp:GridView>
Related Topic