How to create a nested GridView to edit EF Code First relation?
I've got a classic Parent-Child relation that I would like to CRUD by using asp:GridView
controls. To CRUD the parent is easy, but the challenge is to nest a asp:GridView
within a asp:GridView
that is able to work on the child relation.
To make the problem easier, I've constructed an example. Consider the following EF-code:
public class Context : DbContext
{
public DbSet<Animal> Animals { get; set; }
public DbSet<Tag> Tags { get; set; }
}
public class Animal
{
public int AnimalID { get; set; }
public string Name { get; set; }
public virtual IEnumerable<Tag> Tags { get; set; }
}
public class Tag
{
public int TagID { get; set; }
public string Name { get; set; }
}
I'm using an asp:Gridview
to view / edit the Animal
objectes:
<asp:GridView runat="server" DataSourceID="animalDataSource" DataKeyNames="AnimalID" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:CommandField ShowCancelButton="true" ShowEditButton="true" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
The DataSource
is bound with code behind:
protected void DataSource_ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)
{
var context = new Context();
e.Context = ((IObjectContextAdapter)context).ObjectContext; }
}
I would like to include a nested asp:Gridview
as one of the columns to add / remove / edit Tag
objects beloning to that Animal
. How could I achieve th开发者_StackOverflowis?
The BoundField displays the value of specified DataSource field as text. By using bound field we can bind the data directly by using header text and datafield without using any controls. . The TemplateField allows for a mix of HTML markup, Web controls, and data-binding syntax. We can define our own asp.net controls in template field. so basically you convert a bound field to a template column Template columns also come with a edit template tag which offers you more than the standard editing of that gridview row is desired... e.g when in edit mode put a drop down list in this row for me to select from - possibilities are endless so
change to template field go to edit
template add grid control to field
add Edit/delete link button to it
- go on the property of nested grid under edit template
- find update, row databounfd event etc
i think this will help
Dim grd1 As GridViewRow
Dim gv As GridView Dim l1, l2 As Label Dim strsql As String For Each grd1 In GridView1.Rows 'find controls of parent gridrow l1 = grd1.FindControl("l00") l2 = grd1.FindControl("l1") gv = grd1.FindControl("gv1") strsql = "select file_name from product_file where pname='" & l1.Text & "' and categry='" & l2.Text & "'" Dim dt1 As New DataTable() Dim da1 As New SqlDataAdapter(strsql, con) da1.Fill(dt1) gv.DataSource = dt1 gv.DataBind() Next
do something like this when you fill your parent grid
精彩评论